[go: up one dir, main page]

0% found this document useful (0 votes)
17 views44 pages

Placement Impcodes

Uploaded by

nitinreddy992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views44 pages

Placement Impcodes

Uploaded by

nitinreddy992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Reserve a number.

n=int(input())
t=n
s=0
while n>0:
r=n%10
s=s*10+r
n=n//10
print(s)

Fibonacci Series upto nth term.

Fibonacci sequence is a sequence in which each number is the sum of the two
preceding ones. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ....

n=int(input())
n1, n2 = 0, 1
for i in range(2,n):
n3=n1+n2
n1=n2
n2=n3
print(n3,end=" ")

GCD.

The greatest common divisor (GCD) of two or more numbers is the greatest common
factor number that divides them, exactly. It is also called the highest common factor.

a=int(input())
b=int(input())
def gcd(a, b):
if(b == 0):
return abs(a)
else:
return gcd(b, a % b)
print(gcd(a,b))

LCM.

import math
a,b=map(int,input().split())
print(abs(a*b)//math.gcd(a,b))
Perfect Number.

A positive integer that is equal to the sum of its proper divisors. The smallest perfect
number is 6, which is the sum of 1, 2, and 3.

n=int(input())
s=0
for i in range(1,n):
if(n%i==0):
s=s+i
if(s==n):
print("Perfect")
else:
print("Not Perfect")

Two Strings are Anagram or not.

Two strings are anagrams if they contain the same characters but in a different
order. Note that a letter has to be used only once.

s1=input()
s2=input()
if len(s1)!=len(s2):
print('not anagram')
else:
s1=sorted(s1)
s2=sorted(s2)
if s1==s2:
print('Anagram')
else:
print('Not Anagram')

String is Palindrome or not.

s1=input()
s2=s1[::-1]
if s1==s2:
print('Palindromic')
else:
print('Non Palindromic')
Calculate frequency of characters in a string.

s=input()
c=input()
f=0
f=s.count(c)
print(str(f))

Leap Year or not.

year = int(input())
if (year%400 == 0) or (year%4==0 and year%100!=0):
print("Leap Year")
else:
print("Not a Leap Year")

Find non-repeating characters in string.

s=input()
for i in s:
c=0
for j in s:
if i==j:
c=c+1
if c>1:
break
if c==1:
print(i,end=" ")

Replace a Substring in a string.

s=input()
s1=input()
s2=input()
s=s.replace(s1,s2)
print(s)
Sum of natural numbers using recursion.

def nnrc(n):
if n == 0:
return n
return n + nnrc(n-1)
n = int(input())
print(nnrc(n))

Remove all characters from string except alphabets.

s1=input()
s2=''
for i in s1:
if(ord(i)>=65 and ord(i)<=90) or (ord(i)>=97 and ord(i)<=122):
s2=s2+i
print(s2)

Reverse elements of the array.

def reverseList(A, start, end): #arr=[1,2,3,4,5]


while start < end: #arr.reverse() [OR] #print(arr[::-1])
A[start], A[end] = A[end], A[start] #print(arr)
start += 1
end -= 1
A = list(map(int,input().split()))
reverseList(A, 0, 4)
print(A)
Remove space from a string. #reverse words in a string by joining with(.)

s=input()
s="".join(s.split()) #s=’.’.join(s.split(‘.’)[::-1])
print(s)

Reverse words in a string.

def rev_wrds(s):
words=s.split()
rev_wrd=[word[::-1] for word in words]
rev_str=' '.join(rev_wrd)
return rev_str
s=input()
print(rev_wrds(s))

Factorial of a number.
n=int(input())
f=1
for i in range(2,n+1):
f*=i
print(f)
Binary to decimal convertion.

n=int(input())
binum,dcnum=n,0
base=1
while n>0:
r=n%10
dcnum=dcnum+r*base
n=n//10
base=base*2
print(dcnum)

Automorphic number.

A number is called an Automorphic number if and only if its square ends in the same
digits as the number itself. Ex: 25*25=625 & 76*76=5776.

n=int(input())
l=len(str(n))
sq=n**2
last=sq%pow(10,l)
if last==n:
print('Automorphic')
else:
print('Not Automorphic')
Palindrome number.

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

Print smallest element from array.

arr = list(map(int,input().split()))
mn=arr[0]
for i in range(len(arr)):
if arr[i]<mn:
mn=arr[i]
print(mn)

Sum of digits of a number.

n=int(input())
s=0
while(n!=0):
r=n%10
s+=r
n=n//10
print(s)
Sum of fractions.

import fractions
f1=fractions.Fraction(2,3)
f2=fractions.Fraction(3,7)
print(f1+f2)

Roots of a quadratic equation.

a,b,c=map(int,input().split())
import math
def findRoots(a, b, c):
if a == 0:
print("Invalid")
return -1
d=b*b-4*a*c
sq = math.sqrt(abs(d))
if d > 0:
print("Roots are real and different ")
print((-b + sq)/(2 * a))
print((-b - sq)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else:
print("Roots are complex")
print(- b / (2*a), " + i", sq)
print(- b / (2*a), " - i", sq)
findRoots(a, b, c)

Sorting elements using any algorithm.

def sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
arr = list(map(int,input().split()))
print("Before sorting: ", arr)
arr = sort(arr)
print("After sorting: ", arr)
Search element in a list.

def search(l, key):


for i in range(len(l)):
if (l[i] == key):
return i
return -1
l = list(map(int,input().split()))
key=int(input())
r=search(l,key)
if(r==-1):
print(f"element {key} is not found")
else:
print(f"element {key} is found at index {r}")

Count no. of 1’s in a binary string.

n=int(input())
print(bin(n).count('1')) # print(bin(2)[2:])

Generate all the prime numbers between one & the given number.

a whole number greater than 1 whose only factors are 1 and itself.
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.

def checkPrime(n):
if n < 2:
return 0
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return 0
return 1
r1=int(input())
r2=int(input())
for i in range(r1,r2+1):
if checkPrime(i):
print(i,end=" ")
Heap Sort.

Heap sort is a sorting algorithm that organizes elements in an array into a


binary heap, and then sorts that heap by moving the largest element in the
array.

import heapq
def heap_sort(arr):
heapq.heapify(arr)
result = []
while arr:
result.append(heapq.heappop(arr))
return result
arr = list(map(int,input().split()))
print("Input Array: ", arr)
print("Sorted Array: ", heap_sort(arr))

Sum of individual digits.

n=int(input())
s=0
while n>0:
s+=n%10
n=n//10
print(s)

Reverse words of a string.

s = input()
words = s.split(' ')
string = []
for word in words:
string.insert(0, word)
print(" ".join(string))

n=int(input())
l=list(map(int,input().split()))[:n]
print(' '.join(map(str,l)))
“for printing 1 2 3 instead of [1,2,3] and also avoids EOF error”
Sort alphabets and digits in a string.

s = input()
alphabets=[]
digits=[]
for ch in s:
if ch.isalpha():
alphabets.append(ch)
else:
digits.append(ch)
result="".join(sorted(alphabets)+sorted(digits))
print(result)

Given string is binary or not.

def check(string):
p=set(string)
s = {'0','1'}
if s==p or p== {'0'} or p== {'1'}:
print('Yes')
else:
print('No')
string=input()
check(string)

Add 2 Binary Strings.

a=input()
b=input()
s=bin(int(a,2)+int(b,2))[2:]
print(s)

Find the missing number in the array.

def find_missing_number(arr):
n = len(arr)
total_sum = n * (n + 1) // 2
arr_sum = sum(arr)
missing_number = total_sum - arr_sum
return missing_number
arr = list(map(int,input().split()))
missing_number = find_missing_number(arr)
print(f"The missing number is: {missing_number}")
Valid Parentheses or not.

def isValidParentheses(s):
stack = []
pairs = {'(': ')', '[': ']', '{': '}'}
for char in s:
if char in pairs: # If it's an opening bracket
stack.append(char)
elif stack and pairs[stack[-1]] == char: # If it's a matching closing bracket
stack.pop()
else: # Either unmatched closing bracket or empty stack
return False
return not stack # Return True if stack is empty (all matched)
s = input("Enter a string with brackets: ")
print(isValidParentheses(s))

Remove duplicates and sort given list.

l=list(map(int,input().split()))
r=sorted(list(set(l))) # l=" ".join(map(str, l))
print(r)

Sorting without using predefined functions.

n=int(input())
for _ in range(n):
l=list(map(int,input().split()))
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print(l)
Finding middle element from the list.

def midele(l):
length = len(l)
midx = length // 2
if length % 2 == 0:
mid = math.ceil((l[midx - 1] + l[midx]) / 2)
else:
mid = l[midx]
return mid
import math
l = list(map(int,input().split()))
r = midele(l)
print(r)

Integer to Roman number.

def int_to_roman(num):
roman_nums = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),(100, 'C'), (90,
'XC'), (50, 'L'), (40, 'XL'),(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
result = ''
for val, nm in roman_nums:
while num>=val:
result+=nm
num-=val
return result
num=int(input())
print(int_to_roman(num))

Remove vowels in a string.

string = input()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ""
for i in range(len(string)):
if string[i] not in vowels:
result = result + string[i]
print(result)
Harshad number.

A number is said to be the Harshad number if it is divisible by the sum of its digit.
For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since
156 is divisible by 12. So, 156 is a Harshad number.

def harshad(num):
digits = [int(digit) for digit in str(num)]
s=sum(digits)
return num%s==0
t=int(input())
for i in range(t):
num=int(input())
if harshad(num):
print("Harshad")
else:
print("not Harshad")

String is Isogram or not.

If both strings have the same length, it is an isogram.

def check_isogram(str1):
return len(str1) == len(set(str1.lower()))
print(check_isogram("Python"))

Sum of elements in an array.

n=int(input())
a=list(map(int,input().split()))[:n]
print(sum(a))
Two Sum - Given an array of integers, find two numbers such that they add up
to a specific target number.

def twoSum(nums, target_num):


result_dict = dict()
pos = 0
while pos < len(nums):
if (target_num - nums[pos]) not in result_dict:
result_dict[nums[pos]] = pos
pos += 1
else:
return [target_num - nums[pos], nums[pos]]
return None
nums = list(map(int, input().split()))
target_num = int(input())
r = twoSum(nums, target_num)
print(r)
#return [result_dict[target_num - nums[pos]], pos] –> for index values

Print Nth Fibonacci number.

def Fibonacci(n):
if n == 0 or n==1:
return 0
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
n=int(input())
print(Fibonacci(n))

Prime number or not


def checkPrime(n):
if n < 2:
return 0
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return 0
return 1
Check if the given graph is tree or not.

def isTree(self, n, m, edges):


adj_list = {i: [] for i in range(n)}
for edge in edges:
u, v = edge
adj_list[u].append(v)
adj_list[v].append(u)
visited = set()
def dfs(node, parent):
# If the node is already visited, the graph has a cycle
if node in visited:
return False
visited.add(node)
# Visit neighbors of the current node
for neighbor in adj_list[node]:
# Skip the parent, as it is already visited in the previous step
if neighbor != parent:
if not dfs(neighbor, node):
return False
return True
# Check if the graph is connected and has no cycles
if not dfs(0, -1) or len(visited) != n:
return 0
# If the graph is connected and has no cycles, it is a tree
return 1
Fractional Knapsack problem.

def fractionalknapsack(self, W, arr, n):


c = 0 # To keep track of the total weight in the knapsack.
k = 0 # To keep track of the total value obtained
# Sort the array based on the ratio of value to weight in descending order.
arr.sort(key=lambda x: x.value / x.weight, reverse=True)
# Iterate over each element 'i' in the sorted array 'arr'
for i in arr:
# Check if adding the weight of the current element 'i' does not exceed the
capacity 'W'
if c == W:
break # If the knapsack is already full, break out of the loop
if (c + i.weight) <= W:
# If adding the weight of the current element 'i' does not exceed the capacity'W'
c += i.weight # Add the weight of 'i' to the total weight in the knapsack
k += i.value # Add the value of 'i' to the total value obtained
else:
# If adding the weight of 'i' would exceed the capacity 'W', add a fraction
of 'i' to fill the knapsack
k += i.value * ((W - c) / i.weight)
# Break out of the loop since the knapsack is now full after adding a
fraction of 'i'
break
# Return the total value obtained from the knapsack
return k

Check given string contains digits or not.

def contains_digits(s):
for char in s:
if char.isdigit():
return True
return False
s = input()
if contains_digits(s):
print("The string contains digits.")
else:
print("The string does not contain digits.")
Print the following pattern:

*****
*****
*****
*****
*****

for i in range(1,6):
for j in range(1,6):
print('*',end=" ")
print()

Print the following pattern:

*
**
***
****
*****

for i in range(1,6):
for j in range(i):
print('*',end=" ")
print()

Print the following pattern:

A
AB
ABC
ABCD
ABCDE

s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(i):
print(s[j],end=" ")
print()
Print the following pattern:

E
ED
EDC
EDCB
EDCBA

s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(i):
print(chr(65+5-1-j),end=" ")
print()

Print the following pattern:

ABCDE
ABCD
ABC
AB
A

s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(6-i):
print(chr(65+j),end=" ")
print()

Longest palindromic substring.

def longestPalindrome(s):
max_len = 0
max_word = ""
for first in range(len(s)):
for second in range(first+1, len(s)+1):
word = s[first:second]
if (word == word[::-1]):
if max_len < len(word):
max_len = len(word)
max_word = word
return max_word
s=input()
print(longestPalindrome(s))
Longest common prefix.

def longestCommonPrefix(strings):
if not strings:
return ""
strings.sort()
first = strings[0]
last = strings[-1]
prefix = ""
for i in range(len(first)):
if i < len(last) and first[i] == last[i]:
prefix += first[i]
else:
break
return prefix
strings = ["flower", "flow", "flight"]
print(longestCommonPrefix(strings))

Sort the given String as required below:


I/P: Sorting1234
O/P: ginortS1324

s = sorted(input())
low = up = odd = even = ''
for char in s:
if char.islower():
low += char
elif char.isupper():
up += char
elif int(char)%2 == 1:
odd += char
else:
even += char
print(low + up + odd + even)
Rotate List by N positions.

a=int(input())
arr=list(map(int,input().split()))[:a]
n=int(input())
for i in range(n):
temp=arr[0]
arr[0]=arr[a-1]
for j in range(1,a):
s=arr[j]
arr[j]=temp
temp=s
for i in arr:
print(i,end=" ")

Rotate Array to right from k steps.

def rotate(nums, k):


n = len(nums)
k=k%n
nums=nums[-k:]+nums[:-k]
return nums
nums=list(map(int,input().split()))
k=int(input())
print(rotate(nums,k))

Count no of consistent strings.

def countConsistentStrings(l, words):


l_set = set(l)
c=0
for word in words:
if all(char in l_set for char in word):
c+= 1
return c
l="abc"
words=['a','b','c','ab','ac','bc','abc']
print(countConsistentStrings(l,words))
Isomorphic Strings or not.

def isisomorphic(str1, str2):


if len(str1) != len(str2):
return False
else:
map1, map2 = {}, {}
for i in range(len(str1)):
ch1, ch2 = str1[i], str2[i]
if ch1 not in map1:
map1[ch1] = ch2
if ch2 not in map2:
map2[ch2] = ch1
if map1[ch1] != ch2 or map2[ch2] != ch1:
return False
return True
str1 = "abacba"
str2 = "xpxcpx"
print(isisomorphic(str1, str2))

Maximum words found in sentences.

def WordsFound(sentences):
max_words = 0
for sentence in sentences:
words = sentence.split()
num_words = len(words)
if num_words > max_words:
max_words = num_words
return max_words
sentences=["Dattu has very big boobs", "Nitin is fucking handsome baby boo"]
print(WordsFound(sentences))
Ugly Number or not.

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
def isUgly(num):
if num <= 0:
return 'Not an Ugly Number'
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return "Ugly Number" if num == 1 else "Not an Ugly Number"
num=int(input())
print(isUgly(num))

Calculate frequency of the keys present in the array.

a=[1,3,4,2,2,1,4,7,7]
d={}
for i in a:
if i in d:
d[i]+=1
else:
d[i]=1
print(d)

0/1 Knapsack Problem.

def knapSack(self,W, wt, val, n):


dp = [[0 for _ in range(W+1)] for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, W+1):
if wt[i-1] <= j:
dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j])
else:
dp[i][j] = dp[i-1][j]
return dp[n][W]
Stack program.

class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return "Stack is empty"
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def display(self):
print(self.items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.display() # Output: [1, 2, 3]
print(stack.pop()) # Output: 3
stack.display() # Output: [1, 2]
print(stack.peek()) # Output: 2
print(stack.is_empty()) # Output: False
print(stack.size()) # Output: 2
Queue program.

class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, data):
new_node = Node(data)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.is_empty():
print("Queue is empty")
return None
temp = self.front
self.front = temp.next
if self.front is None:
self.rear = None
return temp.data
def display(self):
if self.is_empty():
print("Queue is empty")
return
current_node = self.front
nodes = []
while current_node:
nodes.append(current_node.data)
current_node = current_node.next
print(" <- ".join(map(str, nodes)))
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.display() # Output: 1 <- 2
print(queue.dequeue()) # Output: 1
Nearest Prime Number.

def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def nearest_prime(n):
if is_prime(n):
return n
lower = n - 1
while lower > 1:
if is_prime(lower):
return lower
lower -= 1
def print_unique_nearest_primes_up_to(n):
seen_primes = set()
for i in range(2, n):
nearest = nearest_prime(i)
if nearest not in seen_primes:
print(nearest)
seen_primes.add(nearest)
n = int(input())
print_unique_nearest_primes_up_to(n)

Kth Largest element in an array.

def find_kth_largest(arr, k):


arr.sort(reverse=True)
return arr[k - 1]
arr = list(map(int,input().split()))
k=2
result = find_kth_largest(arr, k)
print(f"The {k}-th largest element is {result}")
Reverse a Linked list.

class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def reverse(self):
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
print()
llist = LinkedList()
llist.push(1)
llist.push(2)
llist.push(3)
llist.push(4)
print("Original Linked List:")
llist.print_list()
llist.reverse()
print("Reversed Linked List:")
llist.print_list()
Binary tree is BST or not.

class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_bst_util(node, left, right):
# Base case: An empty tree is a BST
if node is None:
return True
# If this node violates the min/max constraint, it's not a BST
if node.data <= left or node.data >= right:
return False
# Recursively check the left and right subtrees
return (is_bst_util(node.left, left, node.data) and
is_bst_util(node.right, node.data, right))
def is_bst(root):
# Initialize with the minimum and maximum possible values
return is_bst_util(root, float('-inf'), float('inf'))
root = Node(10)
root.left = Node(5)
root.right = Node(20)
root.left.left = Node(1)
root.left.right = Node(8)
root.right.left = Node(15)
root.right.right = Node(30)
if is_bst(root):
print("The tree is a binary search tree.")
else:
print("The tree is not a binary search tree.")
Merge 2 sorted arrays.

def merge_sorted_arrays(arr1, arr2):


merged_array = []
i, j = 0, 0
# Merge the two arrays by comparing elements
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1
# Append remaining elements from arr1 (if any)
while i < len(arr1):
merged_array.append(arr1[i])
i += 1
while j < len(arr2):
merged_array.append(arr2[j])
j += 1
return merged_array
arr1 = [1, 3, 5, 7]
arr2 = [2, 4, 6, 8]
result = merge_sorted_arrays(arr1, arr2)
print("Merged array:", result)
Python Interview Questions:

Easy Questions

1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity
and readability. It supports multiple programming paradigms, including
procedural, object-oriented, and functional programming.

2. What are the key features of Python?


Python is known for its easy-to-read syntax, dynamic typing, automatic memory
management, a large standard library, and support for both small and large-scale
projects.

3. How do you create a list in Python?


Lists are created using square brackets. For example: my_list = [1, 2, 3].

4. How can you convert a string to a number in Python?


Use the int(), float(), or complex() functions to convert a string to an integer, float,
or complex number, respectively.

5. What is the difference between append() and extend() methods for lists?
append() adds a single element to the end of a list, while extend() adds multiple
elements by appending elements from an iterable like another list.

6. Explain the difference between remove() and pop() methods for lists.
remove() deletes the first occurrence of a specified value, whereas pop() removes
and returns the element at a specified index.

7. What is a tuple in Python?


A tuple is an immutable ordered collection of elements, defined using parentheses.
For example: my_tuple = (1, 2, 3).

8. How do you create a dictionary in Python?


Dictionaries are created using curly braces with key-value pairs. For example:
my_dict = {‘key’: ‘value’}.

9. What is a set in Python?


A set is an unordered collection of unique elements. Sets are defined using curly
braces: my_set = {1, 2, 3}.

10. What is the purpose of the pass statement in Python?


pass is a null statement used as a placeholder in functions, loops, or classes where
code is syntactically required but no action is needed.

11. What are Python keywords?


Keywords are reserved words that have special meanings in Python, such as if,
else, for, while, return, True, False, and None.

12. What are Python literals?


Literals represent fixed values in Python. Examples include string literals
(“Hello”), numeric literals (123), boolean literals (True, False), and special literal
(None).

13. What is the difference between .py and .pyc files?


.py files contain Python source code, while .pyc files contain the bytecode that the
Python interpreter generates from the .py files for faster execution.

14. Explain slicing in Python.


Slicing is used to access a range of elements in sequences like lists, tuples, and
strings. Syntax: sequence[start:end:step].

15. What is a Python module?


A module is a file containing Python definitions and statements. Modules allow
for code reuse and organization.

Medium Questions

1. What is a lambda function in Python?


A lambda function is a small anonymous function defined with the lambda
keyword. It can have multiple arguments but only one expression. Example:
lambda x: x + 1.

2. Explain the difference between map() and filter() functions.


map() applies a function to all items in an iterable and returns a list of results.
filter() returns a list of items for which a function returns True.

3. What is a decorator in Python?


A decorator is a function that modifies another function, adding functionality
without changing its structure. Decorators are denoted with the @ symbol.

4. Explain the concept of *args and **kwargs.


*args allows a function to accept any number of positional arguments, which are
passed as a tuple. **kwargs allows a function to accept keyword arguments,
passed as a dictionary.
5. What is recursion in Python?
Recursion is a function calling itself to solve a smaller instance of the same
problem. Example: calculating the factorial of a number.

6. Explain the purpose of the global keyword in Python.


The global keyword is used to declare that a variable inside a function is global
and should not be treated as a local variable.

7. What is dictionary comprehension?


Dictionary comprehension is a concise way to create dictionaries. Syntax: {key:
value for item in iterable}.

8. What is the nonlocal keyword in Python?


The nonlocal keyword is used to indicate that a variable inside a nested function
refers to a variable in the enclosing scope.

9. How can you handle exceptions in Python?


Use try, except, else, and finally blocks to handle exceptions. This structure allows
for graceful error handling.

10. What is the difference between shallow copy and deep copy?
A shallow copy creates a new object but inserts references into it. A deep copy
creates a new object and recursively copies all objects found in the original.

11. What is the Global Interpreter Lock (GIL)?


The GIL is a mutex that protects access to Python objects, preventing multiple
threads from executing Python bytecodes simultaneously.

12. Explain the concept of generators in Python.


Generators are iterators that yield items instead of returning them all at once. They
are defined using the yield keyword.

13. What are metaclasses in Python?


Metaclasses define the behavior of classes and are themselves classes of classes.
They allow for the customization of class creation.

14. How does memory management work in Python?


Memory management in Python involves private heap space, managed by
Python’s memory manager and supported by garbage collection.

15. What is monkey patching in Python?


Monkey patching refers to dynamic modifications of a class or module at runtime.
Hard Questions

1. Explain the difference between __init__ and __new__ methods.


__init__ initializes an instance after it is created. __new__ is responsible for
creating a new instance of a class.

2. How do you implement multithreading in Python?


Multithreading can be implemented using the threading module. Python threads
are not truly parallel due to the GIL, but they can be useful for I/O-bound tasks.

3. What are the built-in data types in Python?


Python’s built-in data types include numeric types (int, float, complex), sequence
types (str, list, tuple, range), mapping types (dict), set types (set), and boolean
types (bool).

4. What is the difference between == and is operators?


== checks for value equality, while is checks for object identity, i.e., whether two
variables reference the same object.

5. What is the purpose of the if __name__ == “__main__”: statement?


This statement ensures that code block runs only when the script is executed
directly, not when imported as a module.

6. What is the difference between a shallow copy and a deep copy?


A shallow copy copies an object but not the objects it references. A deep copy
recursively copies the object and all objects it references.

7. Explain the use of decorators in Python.


Decorators modify the behavior of a function or method. They are often used to
extend functionalities without changing the original function’s code.

8. What is the purpose of self in class methods?


self refers to the instance of the class, allowing access to the attributes and
methods of the class within its methods.

9. How do you handle exceptions in Python?


Exceptions are handled using try, except, else, and finally blocks. This allows for
graceful error handling and resource cleanup.

10. What is polymorphism in Python?


Polymorphism allows methods to do different things based on the object it is
acting upon, enabling different classes to be treated through the same interface.
Basic Data Structure Interview Questions for Freshers

1. What is a Data Structure?


The Data Structure is the way data is organized (stored) and manipulated for
retrieval and access. It also defines the way different sets of data relate to one
another, establishing relationships and forming algorithms.

2. Describe the types of Data Structures?


The following are the types of data structures:
Lists: A collection of related things linked to the previous or/and following data
items.
Arrays: A collection of values that are all the same.
Records: A collection of fields, each of which contains data from a single data
type.
Trees: A data structure that organizes data in a hierarchical framework. This form
of data structure follows the ordered order of data item insertion, deletion, and
modification.
Tables: The data is saved in the form of rows and columns. These are comparable
to records in that the outcome or alteration of data is mirrored across the whole
table.

3. What is a Linear Data Structure? Name a few examples.


A data structure is linear if all its elements or data items are arranged in a sequence
or a linear order. The elements are stored in a non-hierarchical way so that each
item has successors and predecessors except the first and last element in the list.
Examples of linear data structures are Arrays, Stack, Strings, Queue, and Linked
List.

4. What are some applications of Data Structures?


In terms of data structure interview questions, this is one of the most frequently
asked question.
Numerical analysis, operating system, AI, compiler design, database management,
graphics, statistical analysis, and simulation.

5. What is the difference between file structure and storage structure?


The difference lies in the memory area accessed. Storage structure refers to the
data structure in the memory of the computer system, whereas file structure
represents the storage structure in the auxiliary memory.

6. What is a multidimensional array?


A multidimensional array is a multidimensional array with more than one
dimension. It is an array of arrays or an array with numerous layers. The 2D array,
or two-dimensional array, is the most basic multidimensional array. As you'll see
in the code, it's technically an array of arrays. A 2D array is also referred to as a
matrix or a table with rows and columns. Declaring a multidimensional array is the
same as saying a one-dimensional array. We need to notify C that we have two
dimensions for a two-dimensional array.

7. How are the elements of a 2D array stored in the memory?


Row-Major Order: -In row-major ordering, all of the rows of a 2D array are stored
in memory in a contiguous manner.
First, the first row of the array is entirely stored in memory, followed by the
second row of the array, and so on until the final row.
Column-Major Order: In column-major ordering, all of the columns of a 2D array
are stored in memory in the same order. The first column of the array is entirely
saved in memory, followed by the second row of the array, and so on until the last
column of the array is wholly recorded in memory.

8. What is a linked list Data Structure?


This is one of the most frequently asked data structure interview questions where
the interviewer expects you to give a thorough answer. Try to explain as much as
possible rather than finishing your answer in a sentence!
It’s a linear Data Structure or a sequence of data objects where elements are not
stored in adjacent memory locations. The elements are linked using pointers to
form a chain. Each element is a separate object, called a node. Each node has two
items: a data field and a reference to the next node. The entry point in a linked list
is called the head. Where the list is empty, the head is a null reference and the last
node has a reference to null.
A linked list is a dynamic data structure, where the number of nodes is not fixed,
and the list has the ability to grow and shrink on demand.
It is applied in cases where:
We deal with an unknown number of objects or don’t know how many items are in
the list
We need constant-time insertions/deletions from the list, as in real-time computing
where time predictability is critical
Random access to any elements is not needed
The algorithm requires a data structure where objects need to be stored
irrespective of their physical address in memory
We need to insert items in the middle of the list as in a priority queue
Some implementations are stacks and queues, graphs, directory of names, dynamic
memory allocation, and performing arithmetic operations on long integers.

9. Are linked lists considered linear or non-linear Data Structures?


Linked lists are considered both linear and non-linear data structures depending
upon the application they are used for. When used for access strategies, it is
considered as a linear data-structure. When used for data storage, it is considered a
non-linear data structure.

10. What are the advantages of a linked list over an array? In which scenarios do
we use Linked List and when Array?
This is another frequently asked data structure interview questions! Advantages of
a linked list over an array are:
i. Insertion and Deletion
Insertion and deletion of nodes is an easier process, as we only update the address
present in the next pointer of a node. It’s expensive to do the same in an array as
the room has to be created for the new elements and existing elements must be
shifted.
ii. Dynamic Data Structure
As a linked list is a dynamic data structure, there is no need to give an initial size
as it can grow and shrink at runtime by allocating and deallocating memory.
However, the size is limited in an array as the number of elements is statically
stored in the main memory.
iii. No Wastage of Memory
As the size of a linked list can increase or decrease depending on the demands of
the program, and memory is allocated only when required, there is no memory
wasted. In the case of an array, there is memory wastage. For instance, if we
declare an array of size 10 and store only five elements in it, then the space for
five elements is wasted.
iv. Implementation
Data structures like stack and queues are more easily implemented using a linked
list than an array.
Some scenarios where we use linked list over array are:
When we know the upper limit on the number of elements in advance
When there are a large number of add or remove operations
When there are no large number of random access to elements
When we want to insert items in the middle of the list, such as when implementing
a priority queue
Some scenarios in which we use array over the linked list are:
When we need to index or randomly access elements
When we know the number of elements in the array beforehand, so we can
allocate the correct amount of memory
When we need speed when iterating through all the elements in the sequence
When memory is a concern; filled arrays use less memory than linked lists, as each
element in the array is the data but each linked list node requires the data as well
as one or more pointers to the other elements in the linked list
In summary, we consider the requirements of space, time, and ease of
implementation to decide whether to use a linked list or array.
11. What is a doubly-linked list? Give some examples.
It is a complex type (double-ended LL) of a linked list in which a node has two
links, one that connects to the next node in the sequence and another that connects
to the previous node. This allows traversal across the data elements in both
directions.
Examples include:
A music playlist with next and previous navigation buttons
The browser cache with BACK-FORWARD visited pages
The undo and redo functionality on a browser, where you can reverse the node to
get to the previous page

12. How do you reference all of the elements in a one-dimension array?


Using an indexed loop, we may access all of the elements in a one-dimensional
array. The counter counts down from 0 to the maximum array size, n, minus one.
The loop counter is used as the array subscript to refer to all items of the one-
dimensional array in succession.

13. What are dynamic Data Structures? Name a few.


They are collections of data in memory that expand and contract to grow or shrink
in size as a program runs. This enables the programmer to control exactly how
much memory is to be utilized.
Examples are the dynamic array, linked list, stack, queue, and heap.

14. What is an algorithm?


An algorithm is a step by step method of solving a problem or manipulating data.
It defines a set of instructions to be executed in a certain order to get the desired
output.

15. Why do we need to do an algorithm analysis?


A problem can be solved in more than one way using several solution algorithms.
Algorithm analysis provides an estimation of the required resources of an
algorithm to solve a specific computational problem. The amount of time and
space resources required to execute is also determined.
The time complexity of an algorithm quantifies the amount of time taken for an
algorithm to run as a function of the length of the input. The space complexity
quantifies the amount of space or memory taken by an algorithm, to run as a
function of the length of the input.

16. What is a stack?


A stack is an abstract data type that specifies a linear data structure, as in a real
physical stack or piles where you can only take the top item off the stack in order
to remove things. Thus, insertion (push) and deletion (pop) of items take place
only at one end called top of the stack, with a particular order: LIFO (Last In First
Out) or FILO (First In Last Out).

17. Where are stacks used?


Expression, evaluation, or conversion of evaluating prefix, postfix, and infix
expressions
Syntax parsing
String reversal
Parenthesis checking
Backtracking

18. What are the operations that can be performed on a stack?


A stack is a linear data structure that operates on the same concept, in that
components in a stack are added and deleted only from one end, referred to as the
TOP. As a result, a stack is known as a LIFO (Last-In-First-Out) data structure
because the piece that was put last is the first to be removed.
A stack may perform three fundamental operations:
PUSH: The push action inserts a new element into the stack. The new feature is
placed at the top of the stack. However, before inserting the value, we must first
verify if TOP=MAX–1, since if so, the stack is filled, and no more insertions are
possible. An OVERFLOW message is printed if an attempt is made to put a value
into an existing stack.
POP: The pop operation is performed to remove the stack's topmost element.
However, before removing the value, we must first verify if TOP=NULL, since if
it is, the stack is empty, and no further deletions are permitted. An UNDERFLOW
notice is produced if an attempt is made to erase a value from a stack that is
already empty.
PEEK: A peek action returns the value of the stack's topmost element without
removing it from the stack. On the other hand, the Peek operation first checks if
the stack is empty, i.e., if TOP = NULL, then an appropriate message is written.
Otherwise, a value is returned.
Data Structure Interview Questions for Experienced

19. What is a postfix expression?


A postfix expression is made up of operators and operands, with the operator
coming after the operands. That is, in a postfix expression, the operator comes
after the operands. Likewise, what is the proper postfix form? The correct postfix
phrase is A B + C *.

20. What is a queue Data Structure?


In this type of data structure interview questions, you can also discuss your
experience and situations using queue. A queue is an abstract data type that
specifies a linear data structure or an ordered list, using the First In First Out
(FIFO) operation to access elements. Insert operations can be performed only at
one end called REAR and delete operations can be performed only at the other end
called FRONT.

21. List some applications of queue Data Structure.


To prioritize jobs as in the following scenarios:
As waiting lists for a single shared resource in a printer, CPU, call center systems,
or image uploads; where the first one entered is the first to be processed
In the asynchronous transfer of data; or example pipes, file IO, and sockets
As buffers in applications like MP3 media players and CD players
To maintain the playlist in media players (to add or remove the songs)

22. What is a Dequeue?


It is a double-ended queue, or a data structure, where the elements can be inserted
or deleted at both ends (FRONT and REAR).

23. What operations can be performed on queues?


enqueue() adds an element to the end of the queue
dequeue() removes an element from the front of the queue
init() is used for initializing the queue
isEmpty tests for whether or not the queue is empty
The front is used to get the value of the first data item but does not remove it
The rear is used to get the last item from a queue

24. What are the advantages of the heap over a stack?


In this data structure interview questions, try giving various advantages, along
with examples, if possible. It will show the interviewer your domain expertise.
Generally, both heap and stack are part of memory and used in Java for different
needs:
Heap is more flexible than the stack because memory space can be dynamically
allocated and de-allocated as needed
Heap memory is used to store objects in Java, whereas stack memory is used to
store local variables and function call
Objects created in the heap are visible to all threads, whereas variables stored in
stacks are only visible to the owner as private memory
When using recursion, the size of heap memory is more whereas it quickly fill-ups
stack memory

25. Where can stack Data Structure be used?


Expression evaluation
Backtracking
Memory management
Function calling and return
26. What is the difference between a PUSH and a POP?
In terms of data structure interview questions, this is one of the most frequently
asked question.
The acronyms stand for Pushing and Popping operations performed on a stack.
These are ways data is stored and retrieved.
PUSH is used to add an item to a stack, while POP is used to remove an item.
PUSH takes two arguments, the name of the stack to add the data to and the value
of the entry to be added. POP only needs the name of the stack.
When the stack is filled and another PUSH command is issued, you get a stack
overflow error, which means that the stack can no longer accommodate the last
PUSH. In POP, a stack underflow error occurs when you’re trying to POP an
already empty stack.

27. Which sorting algorithm is considered the fastest? Why?


A single sorting algorithm can’t be considered best, as each algorithm is designed
for a particular data structure and data set. However, the QuickSort algorithm is
generally considered the fastest because it has the best performance for most
inputs.
Its advantages over other sorting algorithms include the following:
Cache-efficient: It linearly scans and linearly partitions the input. This means we
can make the most of every cache load.
Can skip some swaps: As QuickSort is slightly sensitive to input that is in the right
order, it can skip some swaps.
Efficient even in worst-case input sets, as the order is generally random.
Easy adaption to already- or mostly-sorted inputs.
When speed takes priority over stability.

28. What is the merge sort? How does it work?


Merge sort is a divide-and-conquer algorithm for sorting the data. It works by
merging and sorting adjacent data to create bigger sorted lists, which are then
merged recursively to form even bigger sorted lists until you have one single
sorted list.

29. How does the Selection sort work?


This is one of the most frequently asked data structure interview questions.
Selection sort works by repeatedly picking the smallest number in ascending order
from the list and placing it at the beginning. This process is repeated moving
toward the end of the list or sorted subarray.
Scan all items and find the smallest. Switch over the position as the first item.
Repeat the selection sort on the remaining N-1 items. We always iterate forward (i
from 0 to N-1) and swap with the smallest element (always i).
Time complexity: best case O(n2); worst O(n2)
Space complexity: worst O(1)

30. What is an asymptotic analysis of an algorithm?


Asymptotic analysis is the technique of determining an algorithm's running time in
mathematical units to determine the program's limits, also known as "run-time
performance." The purpose is to identify the best case, worst case, and average-
case times for completing a particular activity. While not a deep learning training
technique, Asymptotic analysis is an essential diagnostic tool for programmers to
analyze an algorithm's efficiency rather than its correctness.

31. What are asymptotic notations?


Asymptotic Notation represents an algorithm's running time - how long an
algorithm takes with a given input, n. Big O, large Theta (), and big Omega () are
the three distinct notations. When the running time is the same in all
circumstances, big- is used, big-O for the worst-case running time, and big- for the
best case running time.

32. What are some examples of divide and conquer algorithms?


Quicksort is the name of a sorting algorithm. The method selects a pivot element
and rearranges the array elements so that all items less than the pivot chosen
element go to the left side of the pivot and all elements more significant than the
pivot element move to the right side.
Merge Sort is a sorting algorithm as well. The algorithm divides the array into two
halves, sorts them recursively, and then combines the two sorted halves. The goal
of points that are closest together is to identify the nearest pair of points in an x-y
plane collection of points. The issue may be solved in O(n2) time by computing
the distances between each pair of locations and comparing them to determine the
shortest distance.

33. Define the graph Data Structure?


It is a type of non-linear data structure that consists of vertices or nodes connected
by edges or arcs to enable storage or retrieval of data. Edges may be directed or
undirected.

34. What are the applications of graph Data Structure?


Transport grids where stations are represented as vertices and routes as the edges
of the graph
Utility graphs of power or water, where vertices are connection points and edge
the wires or pipes connecting them
Social network graphs to determine the flow of information and hotspots (edges
and vertices)
Neural networks where vertices represent neurons and edge the synapses between
them.
35. List the types of trees?
Data structure interview questions like this are very common and frequently asked
The General Tree
A tree is referred to as a generic tree if its hierarchy is not constrained. In the
General Tree, each node can have an endless number of offspring, and all other
trees are subsets of the tree.
The Binary Tree
The binary tree is a type of tree in which each parent has at least two offspring.
The children are referred to as the left and right youngsters. This tree is more
popular than most others. When specific limitations and features are given to a
Binary tree, various trees such as AVL tree, BST (Binary Search Tree), RBT tree,
and so on are also utilized.
Tree of Binary Search
Binary Search Tree (BST) is a binary tree extension that includes numerous
optional constraints. In BST, a node's left child value should be less than or equal
to the parent value, while the correct child value should always be higher than or
equal to the parent's value.
The AVL Tree
The AVL tree is a self-balancing binary search tree. The term AVL is given in
honor of the inventors Adelson-Velshi and Landis. This was the first tree to
achieve dynamic equilibrium. Each node in the AVL tree is assigned a balancing
factor based on whether the tree is balanced or not. The node kids have a
maximum height of one AVL vine.
Red and Black Tree
Red-black trees are another type of auto-balancing tree. The red-black term is
derived from the qualities of the red-black tree, which has either red or black
painted on each node. It helps to keep the forest in balance. Even though this tree
is not perfectly balanced, the searching process takes just O (log n) time.
The N-ary Tree
In this sort of tree with a node, N is the maximum number of children. A binary
tree is a two-year tree since each binary tree node has no more than two offspring.
A full N-ary tree is one in which the children of each node are either 0 or N.

36. What are Binary trees?


A binary tree is a tree data structure made up of nodes, each of which has two
offspring, known as the left and right nodes. The tree begins with a single node
called the root.
Each node in the tree carries the following information:
Data
A pointing device indicates the left kid.
An arrow pointing to the correct child
37. What are the differences between the B tree and the B+ tree?
The B tree is a self-balancing m-way tree, with m defining the tree's order.
Depending on the number of m, Btree is an extension of the Binary Search tree in
which a node can have more than one key and more than two children. The data is
provided in the B tree in a sorted manner, with lower values on the left subtree and
higher values on the right subtree.
The B+ tree is an advanced self-balanced tree since every path from the tree's root
to its leaf is the same length. The fact that all leaf nodes are the same length
indicates that they all occur at the same level. Specific leaf nodes can’t appear at
the third level, while others appear at the second level.

38. What are the advantages of binary search over a linear search?
In a sorted list:
A binary search is more efficient than a linear search because we perform fewer
comparisons. With linear search, we can only eliminate one element per
comparison each time we fail to find the value we are looking for, but with the
binary search, we eliminate half the set with each comparison.
Binary search runs in O(log n) time compared to linear search’s O(n) time. This
means that the more of the elements present in the search array, the faster is binary
search compared to a linear search.

39. What is an AVL tree?


An AVL (Adelson, Velskii, and Landi) tree is a height balancing binary search
tree in which the difference of heights of the left and right subtrees of any node is
less than or equal to one. This controls the height of the binary search tree by not
letting it get skewed. This is used when working with a large data set, with
continual pruning through insertion and deletion of data.

40. Differentiate NULL and VOID


Null is a value, whereas Void is a data type identifier
Null indicates an empty value for a variable, whereas void indicates pointers that
have no initial size
Null means it never existed; Void means it existed but is not in effect.

41. Do dynamic memory allocations help in managing data? How?


Dynamic memory allocation stores simple structured data types at runtime. It has
the ability to combine separately allocated structured blocks to form composite
structures that expand and contract as needed, thus helping manage data of data
blocks of arbitrary size, in arbitrary order.

42. Name the ways to determine whether a linked list has a loop.
Using hashing
Using the visited nodes method (with or without modifying the basic linked list
data structure)
Floyd’s cycle-finding algorithm

43. List some applications of multilinked structures?


Sparse matrix
Index generation

44. Explain the jagged array.


It is an array whose elements themselves are arrays and may be of different
dimensions and sizes.

45. Explain the max heap Data Structure.


It is a type of heap data structure where the value of the root node is greater than
or equal to either of its child nodes.

46. How do you find the height of a node in a tree?


The height of the node equals the number of edges in the longest path to the leaf
from the node, where the depth of a leaf node is 0.

You might also like