- Welcome Nerds!
- We've made it easy for you, the data nerds, to learn and revise python basics with this document. Firstly, let's talk about WHY?
There are many reasons for choosing python like its Flexible, Easy to Learn, Open Source etc. if not for these definitely consider Python due to its possibilities and ongoing improvement, which will help build amazing products and help businesses.
For Data Engineering python helps you fill in the gaps where normal SQL and Pipeline tools cannot. Moreover, various tools in the market are compatible with Python and allow data engineers to integrate them into their everyday tasks. For other helpful resources on SQL, Python and DSA please head towards: nerdsfornerds.in
- Keep Hustling. Keep Growing.
- Deepanshu Kalra
Expected time to read: 2 days - 3 days
(excluding practice on Leetcode, HackerRank, other resources shared below)
Some topics to revise before your interview
Here are a few important links for you to go through before you start your preparation:
Preparation from the beginning
Python for all
http://learnpythonthehardway.org/book/
https://realpython.com/start-here/
https://realpython.com/learning-paths/
https://github.com/vinta/awesome-python
https://practice.geeksforgeeks.org/courses/fork-python?vC=1
http://docs.python.org/3/tutorial/index.html
http://developers.google.com/edu/python
http://codecademy.com/learn/learn-python-3
http://pythonforbeginners.com/
https://docs.microsoft.com/en-us/learn/paths/beginner-python/
Python for Data Science
https://jakevdp.github.io/PythonDataScienceHandbook/
Python Questions from Top 50 Data Engineer Interview Questions and Answers
- When do you use a list in place of a tuple?
- Credits
- What are tuples?
- A tuple is a data structure in-built in Python to store data, similar to arrays.
- The syntax to declare a tuple is
location = (28.99, 51.34) We use parenthesis () to declare a tuple.
- In order to access a element, we use indexing.
- latitude, longitude = location[0], location[1]
- Tuples also make use of slicing
fruits = ("apple", "banana", "orange") last_fruit = fruits[:-1]
- Tuples can be deleted using the del command
- del last_fruit
What are lists?
Similar to tuple, lists is another built-in data structure of Python to store data. The syntax to declare a list is:
breakfast = ["bread", "butter", "eggs"]
Similar to tuples , list also supports indexing and slicing
- Difference between tuple and lists ?
- A list is mutable while a tuple is not.
- By mutability, I mean we can change the data stored inside the structure.
- Everything in Python is an object. So when I declare a list
numbers = [1,2,3,4,5]
- numbers is an object of the type list containing numbers 1 to 5
- In case I want to change the second element of the list to 6, I will do this
- numbers[1] = 6
- numbers will now contain [1,6,3,4,5]
- Doing the same with a tuple will give me an error.
- TypeError: ‘tuple’ object does not support item assignment
- Suppose you want to delete a slice of the tuple, you will get the following error.
- TypeError: ‘tuple’ object does not support item deletion
Which functions and methods can be used on both tuples and lists?
Both the data structures support the following functions:
len(), max(), min(), sum(), any(), all(), sorted()
What are some common methods in list and tuple:
index(), count()
Methods in list: append(), insert(), remove(), pop(), clear(), sort(), and reverse()
What is a ternary operator in Python ?
Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It allows testing a condition in a single line replacing the multiline if-else making the code compact
val_return = a if a < b else b
- What are negative indices in Python ?
- Python supports “indexing from the end”, that is, negative indexing.
- This means the last value of a sequence has an index of -1, the second last -2, and so on.
names = ["Alice", "Bob", "Charlie", "David", "Emmanuel", "Fiona"] last = names[-1] second_last = names[-2] third_last = names[-3] print(last, second_last, third_last)
List some of the keywords in Python ?
and | def | False | import | not | True __as__ | __del__ | __finally__ | __in__ | __lambda__ | __try__ __assert__ | __elif__ | __for__ | __is__ | __nonlocal__ | __while__ __break__ | __else__ | __from__ | __None__ | __print__ | __with__ __class__ | __except__ | __global__ | __or__ | __return__ | __yield__ __continue__ | __exec__ | __if__ | __pass__ | __raise__ |
Which are some useful string methods in Python ?
- Although Python is riding the hype wave pretty well since its high usage in fields of AI , what are some of the pitfalls of Python as a language?
- 1. Speed: Python is slower than C or C++. But of course, Python is a high-level language, unlike C or C++ it's not closer to hardware.
- 2. Mobile Development: Python is not a very good language for mobile development. It is seen as a weak language for mobile computing.
3. Memory Consumption: Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-types, Python's memory consumption is also high.
4. Database Access: Python has limitations with database access . As compared to the popular technologies like JDBC and ODBC, Python's database access layer is found to be a bit underdeveloped and primitive .
5. Runtime Errors: Python programmers cited several issues with the design of the language. Because the language is dynamically typed , it requires more testing and has errors that only show up at runtime .
- What are the benefits of Python ?
- Beginner's Language
- Simple and Easy to Learn
- Interpreted Language
- Cross-platform language
- Free and Open Source
- Object-Oriented language
- Extensive Libraries
- Integration with other languages
- Databases Connectivity interfaces to all commercial databases
- How do you remove a duplicate from a Python list ?
- Convert the list() to set()
- What is the life cycle of a thread in Python ?
- A Thread is defined in computer science as the smallest unit that can be scheduled in an operating system
- To create a thread, we create a class that we make override the run method of the thread class. Then, we instantiate it.
- A thread that we just created is in a new state. When we make a call to start() on it, it forwards the threads for scheduling. These are in the ready state.
- When execution begins, the thread is in the running state.
- Calls to methods like sleep() and wait() make a thread wait. Such a thread is in the waiting/blocked state.
- When a thread is done waiting or executing, other waiting threads are sent for scheduling.
- A running thread that is done executing terminates and is in the dead state
(https://www.tutorialspoint.com/java/images/Thread_Life_Cycle.jpg
- What is the dict() data structure in Python ?
- It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
- A pair of braces creates an empty dictionary. Something like this
empty_dic = {}
Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary
student = {'name': "Narendra", 'class': "Junior", 'dob': "2002-01-03"}
Dictionaries are sometimes found in other languages as associative memories or associative arrays.
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type , strings and numbers can always be keys
Which are the assignment operators in Python ?
- What is recursion ?
- When a function makes a call to itself, it is termed recursion.
- But then, in order for it to avoid forming an infinite loop, we must have a base condition.
- Let’s take an example.
def facto(n):
if n==1: return 1 return n*facto(n-1) facto(4) # This will compute 4x3x2x1 = 24 What does the function zip() do?
- The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together etc.
- If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
- zip can also work with lists
Syntax: zip(iterator1, iterator2, iterator3 ...) -> zip object
a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica", "Vicky") x = zip(a, b)
Use the tuple() function to display a readable version of the result:
print(tuple(x)) # prints (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
Given the first and last names of all employees in your firm, what data type will you use to store it?
- What does the function range() do?
- The range() function is used to generate a sequence of numbers over time.
- At its simplest, it accepts an integer and returns a range object (a type of iterable)
- Syntax: range([start,] stop [, step]) -> range object
>>> range(5, 10) range(5, 10) >>> >>> list(range(5, 10)) [5, 6, 7, 8, 9]
When range() is called with a single argument it generates a sequence of numbers from 0 up to the argument specified (but not including it). That's why the number 5 is not included in the sequence.
Here the range() function is called with a step argument of 3, so it will return every third element from 1 to 20 (of course not including 20).
>>> >>> range(1, 20, 3) range(1, 20, 3) >>> >>> >>> list(range(1, 20, 3)) [1, 4, 7, 10, 13, 16, 19] >>>
You can also use the step argument to count backwards. step becomes a negative number in that case
>>> >>> list(range(20, 10, -1)) [20, 19, 18, 17, 16, 15, 14, 13, 12, 11] >>> >>> list(range(20, 10, -5)) [20, 15] >>>
- How can you declare multiple assignments in one statement?
- This is one of the most asked interview questions for Python freshers
There are two ways to do this:
First: This assigns 3, 4, and 5 to a, b, and c respectively
>>> a,b,c=3,4,5
Second: Ths assigns 3 to a, b, and c
>>> a=b=c=3 # 14. What is the 'with' keyword in Python?
- The 'with' statement in Python ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks.
- It may be used to open a file, do something, and then automatically close the file at the end.
- It may be used to open a database connection, do some processing, then automatically close the connection to ensure resources are closed and available for others.
- 'with' will cleanup the resources even if an exception is thrown
# 15. What is the PYTHONPATH variable?
- PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program.
- Hence, it must include the Python source library directory and the directories containing Python source code.
- You can manually set PYTHONPATH, but usually, the Python installer will preset it.
# 16. Can you do functional programming (FP) in Python ? If yes, then list the commonly used functions to enforce FP in Python. Function | Description -----------|---------------------------------------------------------- filter() | Filter lets us filter in some values based on conditional logic. map() | Map applies a function to every element in an iterable. reduce() | Reduce repeatedly reduces a sequence pair-wise until we reach a single value. # filter() >>> list(filter(lambda x:x>5,range(8))) # range(8) -> [0,1,2,3,4,5,6,7] # now filter all numbers greater than 5 [6, 7] # map() >>> list(map(lambda x:x**2,range(8))) # range(8) -> [0,1,2,3,4,5,6,7] # now map will apply function x -> x**2 to all numbers from 0 to 7 [0, 1, 4, 9, 16, 25, 36, 49] # reduce() >>> from functools import reduce >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) # step 1 : [-1,3,4,5] # step 2 : [-4,4,5] # step 3 : [-8,5] -13 # 17. Differentiate between the append() and extend() methods of a list.
- append() adds an element to the end of the list
- extend() adds another list to the end of a list.
>>> list1, list2 = [1, 2, 3], [5, 6, 7, 8]
# This is how append() works: >>> list1.append(4) >>> list1 [1, 2, 3, 4]
# And this is how extend() works: >>> list1.extend(list2) >>> list1 [1, 2, 3, 4, 5, 6, 7, 8] # 16. Explain try, raise and finally.
- These are the keywords we use with exception-handling.
- We put risky code under a try block
- Use the raise statement to explicitly raise an error
- Use the finally block to put code that we want to execute anyway.
>>> try: print(1/0)
except ValueError: print("This is a value error")
finally: print("This will print no matter what.") # OUTPUT: print("This will print no matter what.") # This will print no matter what.
Because in the try block we got a DivisionByZeroException and not ValueError, so that is not caught and the 'finally' block is executed.
- What is the enumerate() function in Python?
- enumerate() iterates through a sequence and extracts the index position and its corresponding value too.
>>> for i,v in enumerate(['Python','C++','Scala']): print(i,v)
# OUTPUT: # 0 Python # 1 C++ # 2 Scala # 18. Evaluate the output of the last line in the following code snippet. >>> A0= dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) >>> A1= range(10) >>> A2= sorted([i for i in A1 if i in A0]) >>> A3= sorted([A0[s] for s in A0]) >>> A4= [i for i in A1 if i in A3] >>> A5= {i:i*i for i in A1} >>> A6= [[i,i*i] for i in A1] >>> A0,A1,A2,A3,A4,A5,A6 # 19. Implement a switch case function using Python. # 20. Write a program in Python to count the number of capital letters in a file. import os dir_path = "C:\Users\1090\" filename = "blob.txt" # change working directory to dir_path os.chdir(dir_path) # open the file
with open(filename) as f: cap_count = 0 # read all characters of the file
for char in f.read():
if char.isupper(): cap_count += 1 print(cap_count) for word in
If you installed a module with pip but it doesn’t import in your IDLE, what could it possibly be?
If while installing a package with pip, you get the error No matching installation found, what can you do?
What is the difference between a Python module and a Python library?
- Explain memory management in Python. (Optional: for CS Students)
- Python manages objects by using reference counting.
- This means that the memory manager keeps track of the number of references to each object in the program.
When an object's reference count drops to zero, which means the object is no longer being used, the garbage collector (part of the memory manager) automatically frees the memory from that particular object.
The user need not to worry about memory management as the process of allocation and deallocation of memory is fully automatic. The reclaimed memory can be used by other objects.
- What are lambda expressions in Python ?
- A lambda function is a small anonymous function.
- A lambda function can take any number of arguments, but can only have one expression.
- Syntax: lambda arguments : expression
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10 print(x(5)) # prints 15
- Lambda functions can take any number of arguments
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b print(x(5, 6)) # prints 30
- The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n): return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in
def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) # prints 22
Note: Use lambda functions when an anonymous function is required for a short period of time
What are generators in Python ?
What are iterators in Python ?
What is the difference between an iterator and a generator ?
What do you know about palindromes? Can you implement one in Python?
- A palindrome is a phrase, a word, or a sequence that reads the same forward and backward.
- One such example will be pip An example of such a phrase will be _‘nurses run’_.
- Normal Function Implementation:
def isPalindrome(string): left, right = 0, len(string)-1
while right >= left:
if not string[left] == string[right]: return False left+=1;right-=1 return True isPalindrome('redrum murder') # returns True isPalindrome('CC.') # returns False __Iterator Implementation:__
def isPalindrome(string): left, right = iter(string), iter(string[::-1]) i=0
while i < len(string)/2:
if next(left) != next(right): return False i+=1 return True isPalindrome('redrum murder') # prints True isPalindrome('CC.') # prints False isPalindrome('CCC.') # prints False isPalindrome('CCC') # prints True
- What do you mean by *args and **kwargs?
- In cases when we don’t know how many arguments will be passed to a function, like when we want to pass a list or a tuple of values, we use *args.
def func(*args):
for i in args: print(i) # call the function func() func(3,2,1,4,7) #output >> 3 2 1 4 7
**kwargs takes keyword arguments when we don’t know how many there will be.
def func(**kwargs):
for i in kwargs: print(i,kwargs[i]) func(a=1,b=2,c=7) >> a.1 b.2 c.7
- How will you find, in a string, the first word that rhymes with ‘cake’?
- For our purpose, we will use the search() function, and then use group() to get the output.
- search() will scan through a string, looking for any location where this re matches. It returns None if no match is found.
- Syntax: search(pattern, string)
- group() will return the match found in search(). Defaults to first match
- Syntax: group(index)
- group() and group(0) will give the same output
- In case there are multiple matches found, they can be retrieved using group(index) where index starts from 0
- To access all the matches as a tuple, use groups() function.
- dot ( . ) is a wild card which will match any character except newline
>>> import re >>> rhyme=re.search('.ake','I would make a cake, but I hate to bake') >>> rhyme.group() ‘make’
- Write a regular expression that will accept an email id. Use the re module.
- dot ( . ) is a wild card which will match any character except newline
- [0-9a-zA-Z]+ Any character of character class 0-9 or a-z or A-Z any number of times
- \ is used to escape a special character, in this case .
() is used to specify a group and | stands for __or__
- $ is end of the string
- Reference: [Regular Expressions Cheat Sheet]
>>> import re >>> e = re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$', 'abc@gmail.com') >>> e.group() ‘abc@gmail.com’
Important Internet Sources
- Leetcode
- Geek for Geeks
https://www.techinterviewhandbook.org/best-practice-questions/
https://docs.google.com/spreadsheets/d/1A2PaQKcdwO_lwxz9bAnxXnIQayCouZP6d-ENrBz_NXc/edit#gid=0
https://thedatamonk.com/the-data-monk-booklist/
- Learn Python - Full Course for Beginners [Tutorial]
- Python Tutorials - YouTube
https://cognitiveclass.ai/courses/python-for-data-science
Asked in Interviews
- How to find the middle element of a linked list in one pass ?
- Solution: Start with two pointers p and q. For every second iteration of p, iterate q. When p reaches the end of the linked list. q will be in the middle of the list.
- How to find the loop or cycle in a linked list in one pass ?
- Solution: Start with two pointers p and q. For every second iteration of p, iterate q. If p and q are pointing to the same node, there is a loop or cycle present.
- How to find the kth element from the end of a linked list in one pass ?
Solution: Start with two pointers p and q. When the p pointer reaches upto the kth element, increment q.When p reaches the end of the list. q is pointing to the element 'kth' from the end.
List some real world applications of linked lists ?
Solution:
Image viewer – Previous and next images are linked, hence can be accessed by next and previous button.
Previous and next page in web browser – We can access previous and next urls searched in the web browser by pressing back and next button since they are linked as linked lists.
Music Player – Songs in the music player are linked to previous and next songs. you can play songs either from starting or ending of the list.
What is a data structure ?
Solution: Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data access more efficient. When dealing with the data structure, we not only focus on one piece of data but the different set of data and how they can relate to one another in an organized manner.
Explain the LIFO scheme.
Solution: LIFO is a short form of Last In First Out. It refers to how data is accessed, stored and retrieved. Using this scheme, data that was stored last should be the one to be extracted first. This also means that in order to gain access to the first data, all the other data that was stored before this first data must first be retrieved and extracted.
# 7. What is merge sort ?
Solution: Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones are merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an even bigger sorted list, which continues until you have one single sorted list.
- What is the minimum number of queues to implement a priority queue ?
- Solution: The minimum number of queues needed in this case is two. One queue is intended for sorting priorities while the other queue is used for actual storage of data.
- Which sorting algorithm is the fastest.
Solution: There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort, merge sort, etc. Not one can be considered the fastest because each algorithm is designed for a particular data structure and data set. It would depend on the data set that you would want to sort.
Some common algorithm problems asked in online tests :
Save all leaf nodes of a Binary tree in a Doubly Linked List by using Right node as Next node and Left Node as Previous Node.
# Python program to extract leaf nodes from binary tree # using double linked list # A binary tree node
class Node: # Constructor to create a new node
def __init__(self, data): self.data = data self.left = None self.right = None # Main function which extracts all leaves from a given Binary Tree. # The function returns new root of Binary Tree (Note that # root may change if Binary Tree has only one node). # The function also sets *head_ref as head of doubly linked list. # left pointer of tree is used as prev in DLL # and right pointer is used as next
def extractLeafList(root): # Base Case
if root is None: return None if root.left is None and root.right is None: # This node is going to be added to doubly linked # list of leaves, set pointer of this node as # previous head of DLL. We don't need to set left # pointer as left is already None root.right = extractLeafList.head # Change the left pointer of previous head
if extractLeafList.head is not None: extractLeafList.head.left = root # Change head of linked list extractLeafList.head = root return None # Return new root # Recur for right and left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) return root # Utility function for printing tree in InOrder
def printInorder(root):
if root is not None: printInorder(root.left) print root.data, printInorder(root.right)
def printList(head):
while(head):
if head.data is not None: print head.data, head = head.right # Driver program to test above function extractLeafList.head = Node(None) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) root.left.left.left = Node(7) root.left.left.right = Node(8) root.right.right.left = Node(9) root.right.right.right = Node(10)
print "Inorder traversal of given tree is:"
printInorder(root) root = extractLeafList(root)
print "\nExtract Double Linked List is:"
printList(extractLeafList.head)
print "\nInorder traversal of modified tree is:"
printInorder(root)
- Given an array,find the maximum j – i such that arr[j] > arr[i]
- Remove Alternate Duplicate characters from a char array you have to do it in Place.Like keeping only the odd occurrences of each character.
- Example: Input: “you got beautiful eyes”
- Output: ”you beautiful es”
- Allowed Time Complexity was O(n) and Space Complexity was O(1)
- In a file there are 1 million words . Find 10 most frequent words in that file.
- Find all nodes at k-distance from a given node in a binary tree
- Clone a linked list with next and random pointer
- Serialise and Deserialise a linked list with next and random pointer.
- Construct a binary tree from given inorder and preorder traversals.
- Return a tree such that each internal node stores the sum of all its child nodes. Each leaf node stores zero.
# 19. How will you implement a linked list with 1 million nodes? How will you access the 999999th node? Give some optimal design strategy and implementation. Reversal of Linked List in groups of K.
- Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.
- Check whether the given binary tree is balanced or not. Definition was no two leaves should have a height difference of greater than one.
- Remove duplicates from the string in place in O(n).
- Connect nodes on the same level in a binary tree.
- Find the sum of data of all leaves of a binary tree on the same level and then multiply sums obtained of all levels.
Given a matrix of characters and a word. You have to count the number of occurrences of that word in that matrix. you can move to any of the eight valid directions from your current position.
- You are given a string as input which represents a path. You have to normalize that path inplace(NO EXTRA SPACE).
- e.g.input : "\a\b\c\..\..\file.txt" output: "\a\file.txt"
- Least common ancestor of two nodes in a binary tree
- Given two sorted arrays (with repetitive elements) find the kth minimum number from both arrays.
- Given the root to a binary tree, a value n and k.Find the sum of nodes at distance k from node with value n
- Find an element in a rotated array. The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling on those days.
- For example, if the given array is {100, 180, 260, 310, 40, 535, 695},
- The maximum profit can be earned by buying on day 0, selling on day 3.
- Again buy on day 4 and sell on day 6.
- If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
- Given two linked lists both represent a number. Create a linked list that contains its sum.
Given a binary search tree , print the path which has the sum equal to k and has minimum hops. i.e if there are multiple paths with the sum equal to k then print the path with minimum number of nodes.
A MxN matrix containing integers (positive, negative and zeros). For every position containing 0, mark the corresponding row and column as 0. Rotate MxN matrix by 90 degrees.
Find the nth number that contains the digit k or is divisible by k. (2 <= k <= 9)
Write a program to connect the next left node in a binary tree. Also the first node of each level should be pointing to the last node of the next level? (Without using Queue)
Convert a binary tree to its sum tree(each node is the sum of its children)
Given a directed graph. Construct another graph from a given graph such that if path exists from vertices A to vertices B and from B to C, then path from A to C and from C to A also should exist.
- Implement hashmap on your own. Write a good hashing function for string.
- Given an array, arrange the elements such that the number formed by concatenating the elements is highest.
- E.g.: input = [9, 93, 24, 6],
- the output should be: [9,93,6,24].
- This is because if you concatenate all the numbers, 993624 is the highest number that can be formed.
- Given a string, find the longest substring which is palindrome.
- Given that integers are read from a data stream. Find the median of elements read in an efficient way. For simplicity assume there are no duplicates.
- Write an efficient program for printing k largest elements in an array. Elements in an array can be in any order.
- Given unsorted array and a number K. Find 2 numbers such that the sum is K.
- Given n-ary tree. zigzag level order traversal.
- Given string s and string t find whether all permutation of t is present as substring in s.
Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. Implement popMin() function which would pop the minimum element from the original stack.
- Given a set of intervals like 5-10, 15-20, 25-40, 30-45, 50-100. Find the ith smallest number in these intervals. Assume there are no duplicate numbers.
- e.g: 1st smallest number = 5 ; 6th smallest number = 10
- 7th smallest number = 15 and so on.
- Given an array which is first strictly increasing and then strictly decreasing. Find an element in this array.
Given a string example : shoppingwithflipkartiseasy. Now we are given this string and a dictionary containing valid words , now we need to break the sentence into words separated by space. Output : shopping with flipkart is easy
Given a series 2,3,4,5,6,8,9,10,……, here in this series all the numbers are present which have factors only and only either 2,3 or 5. Need to write a node to generate the nth number for the series . With best approach and complexity
- Given a tree with edge weights, find any path in the tree with the maximum sum of edges.
- Merge k sorted arrays.
- Given a maze, a start point and end point find the shortest path to reach the end point from the starting point.
- Given a sentence and a set of characters. Find the minimum window within which the set of characters can be found in the sentence in any order.
- You are given a string of 0’s and 1’s you have to find the number of substrings in the string which starts and ends with a 1.
- eg : input : 0010110010 output : 6
- You are given a mapping like a -> 1, b-> 2… z-> 26. You have to print all possible combinations of a given number using the above information.
- eg : input : 121 output : aba,la,au
- Given a dictionary of 50,000 words. Given a phrase without spaces, add spaces to make it a proper sentence.
- e.g:input: thequickbrownfoxjumpoverlazydog
- output: the quick brown fox jump over lazy dog
Given an unsorted array of n integers which can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count frequency of all elements that are present and print the missing elements.
- Examples:Input: arr[] = {2, 3, 3, 2, 5}
- Output: Below are frequencies of all elements
- 1 -> 0 2 -> 2 3 -> 2 4 -> 0 5 -> 1
- Get the next bigger number using the same digits of a number.
- Eg, For 123456, next number would be 123465
- Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands
- Input : mat[][] =
- {{1, 1, 0, 0, 0},
- {0, 1, 0, 0, 1},
- {1, 0, 0, 1, 1},
- {0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}}
Output : 5
Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram?
If two strings contain the same data set in any order then strings are called Anagrams.
Examples:
- Input : str1 = "bcadeh" str2 = "hea"
- Output: 3
- We need to remove b, c and d from str1.
- Input : str1 = "cddgk" str2 = "gcd"
- Output: 2
- Input : str1 = "bca" str2 = "acb"
- Output: 0
- Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Examples:
- Input: arr[] = {2, 0, 2}
- Output: 2
- Structure is like below
| | |_|
- We can trap 2 units of water in the middle gap.
- Input: arr[] = {3, 0, 0, 2, 0, 4}
- Output: 10
- Structure is like below
- |
| | | | | |__|_|
- We can trap "3*2 units" of water between 3 and 2,
- "1 unit" on top of bar 2 and "3 units" between 2
- and 4. See below diagram also.
- Input: arr[] = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
- Output: 6
- |
| || | _|_||_||||||
- Trap "1 unit" between first 1 and 2, "4 units" between
- first 2 and 3 and "1 unit" between second last 1 and last 2
- Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
Insert Remove Replace
All of the above operations are of equal cost.
Examples:
- Input: str1 = "geek", str2 = "gesek"
- Output: 1
- We can convert str1 into str2 by inserting a 's'.
- Input: str1 = "cat", str2 = "cut"
- Output: 1
- We can convert str1 into str2 by replacing 'a' with 'u'.
- Input: str1 = "sunday", str2 = "saturday"
- Output: 3
- Last three and first characters are the same. We basically
- need to convert "un" to "atur". This can be done using
- below three operations.
- Replace 'n' with 'r', insert t, insert a
- Given a string with repeated characters, the task is to rearrange characters in a string so that no two adjacent characters are the same.
- Note : It may be assumed that the string has only lowercase English alphabets.
Examples:
Input: aaabc Output: abaca Input: aaabb Output: ababa Input: aa Output: Not Possible Input: aaaabc Output: Not Possible
- This problem is known as the Clock angle problem where we need to find the angle between hands of an analog clock at a given time.
- Examples:Input: h = 12:00, m = 30.00
- Output: 165 degreeInput: h = 3.00, m = 30.00 Output: 75 degree
- ————————————————————————————————
Ending note
Thank you for reading this. If you found this helpful consider posting about these free documents on LinkedIn.
I would love if you will write about it yourself but for the lazy folks like myself, here’s a sample LinkedIn post:
If you post this you are a hero. Thanks for helping me help others.
My complete interview preparation guide — a living document I maintain and update as I learn. If it helped you, drop me a note on LinkedIn.