You are on page 1of 35

The Best Python Interview Preparation Doc

By Deepanshu Kalra (LinkedIn, Instagram, Twitter)

Read me! 2

Some topics to revise before your interview 3

Preparation from the beginning 4

Python Questions from Top 50 Data Engineer Interview Questions and Answers 5

Important Internet Sources 19

Asked in Interviews 20

Ending note 35

Expected time to read: 2 days - 3 days


(excluding practice on Leetcode, HackerRank, other resources shared below)
Deepanshu Kalra

Read me!
Thanks for all the support and feedback, on the SQL Interview Preparation Doc. You all
encouraged me to create this document for python. I will try to come back and reiterate
over it with time.
Important: The purpose of this document is for you to brush up your Python skills before
the interview.

Please drop a note over LinkedIn:


-if you like this document that would really encourage me
-or if you would like to contribute to this document and make it better.

Bonus Links:
Resume Template: rebrand.ly/deepTemplate
Data Engineering Skills: rebrand.ly/deepDEskills
Individual help (Paid): rebrand.ly/deep1on1

Regards and Happy Learning,


Deepanshu Kalra
Deepanshu Kalra

Some topics to revise before your interview


Here are a few important links for you to go through before you start your preparation:
S.no About Links

1 Covers almost Pythoncheatsheet.org


everything about
Python

2 I would say second https://websitesetup.org/wp-content/uploads/2021/04/Python-che


best at-sheet-April-2021.pdf

3 From Mosh’s https://programmingwithmosh.com/python/python-3-cheat-sheet/


youtube channel

4 GFG to rescue https://www.geeksforgeeks.org/must-know-things-to-clear-your-py


thon-coding-interview/

5 In form of a https://github.com/vishwajeetdabholkar/my-python-learning/blob/
notebook main/Python_Learning.ipynb

[Data Science] Print these and put it on the wall:


https://s3.amazonaws.com/assets.datacamp.com/blog_assets/PythonForDataScience.pdf
https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Python_Bokeh_Cheat_Sheet.pdf
https://s3.amazonaws.com/dq-blog-files/python-cheat-sheet-basic.pdf
https://s3.amazonaws.com/dq-blog-files/python-cheat-sheet-intermediate.pdf

[Others] Print these and put it on the wall:


https://github.com/ehmatthes/pcc/releases/download/v1.0.0/beginners_python_cheat_sheet_pcc_all.
pdf
Deepanshu Kalra

Preparation from the beginning


★ http://learnpythonthehardway.org/book/
★ https://realpython.com/start-here/
★ https://github.com/vinta/awesome-python
★ https://practice.geeksforgeeks.org/courses/fork-python?vC=1
★ http://docs.python.org/3/tutorial/index.html
★ https://calmcode.io/
★ http://developers.google.com/edu/python
★ http://codecademy.com/learn/learn-python-3
★ http://inventwithpython.com/
★ http://learnpython.org/
★ http://pythonforbeginners.com/
★ https://jakevdp.github.io/PythonDataScienceHandbook/
★ https://docs.microsoft.com/en-us/learn/paths/beginner-python/
Deepanshu Kalra

Python Questions from Top 50 Data Engineer


Interview Questions and Answers
# 1. When do you use a list in place of 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

## What are lists ?


Similar to tuple, lists is another built-in data structure of Python to store data
The synatx 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 mutabliity, I mean we can change the data stored inside the
structure

Everything in Python is a 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 lis 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`
Deepanshu Kalra

Suppose you want to delete a slice of the tuple, you will get the following error
`TypeError: ‘tuple’ object does not support item deletion`

## Functions and methods to use on both ?


Both the data structures support the following functions:
`len(), max(), min(), sum(), any(), all(), sorted()`

Common methods in list and tuple: `index(), count()`


Methods in list: `append(), insert(), remove(), pop(), clear(), sort(), and reverse()`

# 2. What is a ternary operator in Python ?


# 3. What are negative indices in Python ?
# 4. 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__ |

# 4. Which are some useful string methods in Python ?


Methods | Description |
--- | --- |
`tolower()` | Converts a string into lower case |
`toupper()` | Converts a string into upper case |
`swapcase()` | Swaps cases, lower case becomes upper case and vice versa |
`islower()` | Returns True if all characters in the string are lower case |
`isupper()` | Returns True if all characters in the string are upper case |
`isalnum()` | Returns True if all characters in the string are alphanumeric |
`isalpha()` | Returns True if all characters in the string are in the alphabet |
`isnumeric()` | Returns True if all characters in the string are numeric |
`capitalize()` | Converts the first character to upper case |
`startswith()` | Returns true if the string starts with the specified value |
`endswith()` | Returs true if the string ends with the specified value |
`replace()` | Returns a string where a specified value is replaced with a specified value |
`split()` | Splits the string at the specified separator, and returns a list |
`splitlines()` | Splits the string at line breaks and returns a list |
`join()` | Joins the elements of an iterable to the end of the string |
`strip()` | Returns a trim version of the string |
`lstrip()` | Returns a left trim version of the string |
`rstrip()` | Returns a right trim version of the string |
`count()` | Returns the number of times a specified value occurs in a string |
`find()` | Searches the string for a specified value and returns the position of where it was found |
Deepanshu Kalra

# 5. 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. [Deepanshu Kalra]

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, the Python's database access layer is found to be 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__ .

# 6. 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

# 6. How do you remove a duplicate from a Python list ?


Convert the `list()` to `set()`

# 7. 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.[Deepanshu Kalra ]
- A thread that we just created is in the 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.
Deepanshu Kalra

- 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

![Life cycle of a thread](https://www.tutorialspoint.com/java/images/Thread_Life_Cycle.jpg)

# 7. 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

# 8. Which are the assignment operators in Python ?


Operator | Description |
--- | --- |
`=` | Assign |
`+=` | Add and Assign |
`-=` | Subtract and Assign |
`*=` | Multiply and Assign |
`/=` | Divide and Assign |
`%=` | Modulus and Assign |
`**=` | Exponent and Assign |
`//=` | Floor Divide and Assign |

# 9. 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:
Deepanshu Kalra

return 1
return n*facto(n-1)

facto(4) # This will compute 4x3x2x1 = 24


```

# 10.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 are 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'))

```
# 11. Given the first and last names of all employees in your firm, what data type will you use to store
it?

# 12.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`

Paramter | Description |
--- | --- |
`start`(optional) | Starting point of the sequence. It defaults to 0. |
`stop` (required) | Endpoint of the sequence. This item will not be included in the sequence. |
`step` (optional) | Step size of the sequence. It defaults to `1`.|
Deepanshu Kalra

```
>>>
>>> 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` upto 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` (off 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]
>>>
```

# 13. How can you declare multiple assignments in one statement?


Deepanshu Kalra

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]
Deepanshu Kalra

# 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)
Deepanshu Kalra

except ValueError:
print("This is a value error")
finally:
print("This will print no matter what.")

# OUTPUT:
# This will print no matter what.
```
Because in the try block we got a __DivisionByZeroException__ and not ValueError, so that is not
caught and `finally` block is executed.

# 17. 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 letter in a file.

```
import os

dir_path = "C:\Users\1090\"
filename = "blob.txt"
Deepanshu Kalra

# 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
```

# 21. If you installed a module with pip but it doesn’t import in your IDLE, what could it possibly be?

# 22. If while installing a package with pip, you get the error No matching installation found, what can
you do?

# 23. What is the difference between a Python module and a Python library?

# 24. 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
de-allocation of memory is fully automatic__. The reclaimed memory can be used by other objects.

# 25. 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
Deepanshu Kalra

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__

# 26. What are generators in Python ?


[ Deepanshu Kalra]
# 27. What are iterators in Python ?

# 28. What is the difference between an iterator and a generator ?

# 29. What do you know about palindromes? Can you implement one in Python?
Deepanshu Kalra

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')
Deepanshu Kalra

# prints True
```

# 30. 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)

func(3,2,1,4,7)
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
```

# 31. 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
Deepanshu Kalra

__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.

`.` is a wild card which will __match any character except newline__
[Deepanshu Kalra]
```
>>> import re
>>> rhyme=re.search('.ake','I would make a cake, but I hate to bake')
>>> rhyme.group()
‘make’
```

# 32. Write a regular expression that will accept an email id. Use the re module.

`.` 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](debuggex.com/cheatsheet/regex/python)

```
>>> import re
>>> e=re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$','abc@gmail.com')
>>> e.group()
‘abc@gmail.com’
```
Deepanshu Kalra

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
Deepanshu Kalra

Asked in Interviews

# 1. How to find the `middle element` of a linked list in one pass ?

Solution: Start with two pointer `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.

# 2. How to find the `loop` or `cycle` in a linked list in one pass ?

Solution: Start with two pointer `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.

# 3. How to find the `k th` element from the end of a linked list in one pass ?

Solution: Start with two pointer `p` and `q`. When the `p` pointer reahces upto the `k th` element,
increment `q`.When `p` reaches the end of the list. `q` is ponting to the element 'k th' from the
end.

# 4. List some real world applications of linked list ?

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 url searched in
web browser by pressing back and next button since, they are linked as linked list.

*Music Player* – Songs in music player are linked to previous and next song. you can play songs
either from starting or ending of the list.

# 5. What is a data structure ?


Deepanshu Kalra

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.

# 6. Explain the `LIFO` scheme.

Solution: LIFO is a short form of Last In First Out. It refers 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.

# 8. What are the minimum number of queues to implement a prioriy 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.

# 9. 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 at online tests :


Deepanshu Kalra

# 10. 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 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:
Deepanshu Kalra

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:


Deepanshu Kalra

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)
Deepanshu Kalra

root = extractLeafList(root)

print "\nExtract Double Linked List is:"

printList(extractLeafList.head)

print "\nInorder traversal of modified tree is:"

printInorder(root)

```

# 11. Given an array,find the maximum j – i such that arr[j] > arr[i]

# 12. Remove Alternate Duplicate characters from a char array you have to do it in Place.Like
keeping only the odd occurences of each character.

`Example: Input: “you got beautiful eyes”

Output: ”you gtbeaiful es”`

Allowed Time Complexity was O(n) and Space Complexity was O(1)

# 13. In a file there are 1 million words . Find 10 most frequent words in that file.

# 14. Find all nodes at k-distance from a given node in a binary tree

## 15. Clone a linked list with next and random pointer

# 16. Serialise and Deserialise a linked list with next and random pointer.

# 17. Construct a binary tree from given inorder and preorder traversals.
Deepanshu Kalra

# 18. Return a tree such that each internal node stores sum of all its child nodes. Each leaf node
stores zero.

# 19. How will you implement linked list with 1 million nodes? How will you access 999999 th
node? Give some optimal design strategy and implementation.

# 20. Reversal of Linked List in groups of K.

# 21. Given a positive integer N, count all possible distinct binary strings of length N such that
there are no consecutive 1’s.

# 22. Check whether given binary tree is balanced or not. Definition was no two leaves should
have height difference of greater than one.

# 23. Remove duplicates from string in place in O(n).

# 24. Connect nodes on same level in a binary tree.

# 25. Find sum of data of all leaves of a binary tree on same level and then multiply sums
obtained of all levels.

# 26. 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 current position.

# 27. You are given an 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"`


Deepanshu Kalra

# 28. Least common ancestor of two nodes in a binary tree

# 29. Given two sorted arrays (with repetitive elements) find the kth minimum number from both
arrays.

# 30. 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

# 31. 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 in those days.

`For example, if the given array is {100, 180, 260, 310, 40, 535, 695},

the maximum profit can 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.`

# 32. Given two linked lists both represent a number. Create a linked list that contains its sum.

# 33. 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.

# 34. A MxN matrix containing integers (positive, negative and zero’s). For every position
containing 0, mark the corresponding row and column as 0. Rotate MxN matrix by 90 degress.

# 35. Find the nth number that contains the digit k or is divisible by k. (2 <= k <= 9)

# 36. Write a program to connect next left node in a binary tree. Also first node of each level
should be pointing to last node of next level? (Without using Queue)
Deepanshu Kalra

# 37. Convert a binary tree to its sum tree(each node is the sum of its children)

# 38. Given a directed graph. Construct another graph from 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
exists.

# 39. Implement hashmap on your own. Write good hashing function for string.

# 40. 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.`

# 41. Given a string, find the longest substring which is palindrome.

# 42. Given that integers are read from a data stream. Find median of elements read so for in
efficient way. For simplicity assume there are no duplicates.

# 43. Write an efficient program for printing k largest elements in an array. Elements in array can
be in any order.

# 44. Given unsorted array and a number K. Find 2 numbers such that sum is K.

# 45. Given n-ary tree. zigzag level order traversal.

# 46. Given string s and string t find whether all permutation of t is present as substring in s.
Deepanshu Kalra

# 47. 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 minimum
element from the original stack.

# 48. 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.`

# 49. Given an array which is first strictly increasing and then strictly decreasing. Find an
element in this array.

# 50. 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

# 51. 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 nth number for the
series . With best approach and complexity

# 52. Given a tree with edge weights, find any path in the tree with maximum sum of edges.

# 53. Merge k sorted arrays.

# 54. Given a maze, a start point and end point find the shortest path to reach the end point from
the starting point.

# 55. 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.
Deepanshu Kalra

# 56. 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 end with a 1.

`eg : input : 0010110010 output : 6`

# 57. 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`

# 58. 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`

# 59. 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`

# 60. Get the next bigger number using the same digits of a number.

`Eg, For 123456, next number would be 123465`

# 61. 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},
Deepanshu Kalra

{0, 0, 0, 0, 0},

{1, 0, 1, 0, 1}}

Output : 5`

# 62. 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 minimum number of characters to be
deleted to make both the strings anagram?

If two strings contains 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``

# 63. 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


Deepanshu Kalra

||

|_|

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 an 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``

# 64. Given two strings str1 and str2 and below operations that can performed on str1. Find
minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.

Insert
Deepanshu Kalra

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 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``

# 65. Given a string with repeated characters, task is rearrange characters in a string so that no
two adjacent characters are same.

Note : It may be assumed that the string has only lowercase English alphabets.
Deepanshu Kalra

``Examples:

Input: aaabc

Output: abaca

Input: aaabb

Output: ababa

Input: aa

Output: Not Possible

Input: aaaabc

Output: Not Possible``

# 66. This problem is know as Clock angle problem where we need to find 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`

————————————————————————————————
Deepanshu Kalra

Ending note
Thank you for reading this. Hope this was helpful.

You might also like