Most Asked Programming Interview Questions
Programming interviews are designed to evaluate more than just your ability to write code. Interviewers often check how well you understand data structures, algorithms, logical problem-solving, and the way you approach a coding problem. Questions based on arrays, linked lists, strings, trees, graphs, and dynamic programming are commonly used to test these skills.
This guide covers frequently asked programming interview questions with Python-based solutions. Practicing these problems can help students and freshers become more comfortable with technical coding rounds.
Table of Contents

YT:- DecodeIT
Arrays
1. How can an array be sorted using Quicksort?
Quicksort works by selecting one element as a pivot and dividing the remaining values into groups based on their relationship with that pivot. The same process is applied to the smaller groups until the complete array becomes ordered.
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
smaller = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
larger = [x for x in arr if x > pivot]
return quicksort(smaller) + equal + quicksort(larger)
2. How do you reverse an array?
One approach is to maintain two positions, one at each end of the array. Swap those values and move both positions toward the middle.
def reverse_array(arr):
left = 0
right = len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
3. How can duplicate values be removed from an array?
A set stores unique values, so it can be used to eliminate repeated elements before converting the result back into a list.
def remove_duplicates(arr):
return list(set(arr))
4. How do you find the second-largest value in an unsorted array?
Keep track of the two largest distinct values while scanning the array once. Whenever a larger value appears, update the first and second positions accordingly.
def second_largest(arr):
largest = second = float('-inf')
for value in arr:
if value > largest:
second = largest
largest = value
elif largest > value > second:
second = value
return second
Linked Lists
1. How can you calculate the length of a linked list?
Start at the head node and move through each next reference. Increase a counter for every node encountered until the pointer becomes None.
def length_of_linked_list(head):
count = 0
current = head
while current:
count += 1
current = current.next
return count
2. How do you reverse a linked list?
The links between nodes can be reversed one at a time. Three references are useful here: the previous node, the current node, and the next node.
def reverse_linked_list(head):
previous = None
current = head
while current:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous
3. How can you locate the third node from the end?
Use two pointers with a gap of three nodes between them. Once the leading pointer reaches the end, the second pointer identifies the required node.
def third_from_end(head):
first = head
second = head
for _ in range(3):
if first is None:
return None
first = first.next
while first:
first = first.next
second = second.next
return second
4. How can duplicate nodes be removed from an unsorted linked list?
A set can remember values that have already appeared. When the next node contains a value already stored in the set, that node can be skipped.
def remove_duplicates(head):
if not head:
return None
seen = {head.data}
current = head
while current.next:
if current.next.data in seen:
current.next = current.next.next
else:
seen.add(current.next.data)
current = current.next
return head
Strings
1. How do you verify that a string contains only digits?
Python provides the isdigit() method for checking whether every character in a string represents a digit.
def is_digit_only(text):
return text.isdigit()
2. How can a string be reversed?
Python slicing provides a short way to read a string from its final character back to its first character.
def reverse_string(text):
return text[::-1]
3. How do you find the first character that appears only once?
First count every character. Then scan the original string again and return the first character whose frequency is one.
def first_non_repeated(text):
frequency = {}
for char in text:
frequency[char] = frequency.get(char, 0) + 1
for char in text:
if frequency[char] == 1:
return char
return None
4. How can duplicate characters be identified?
Count the occurrence of each character with a dictionary and collect characters whose frequency is greater than one.
def find_duplicates(text):
frequency = {}
duplicates = []
for char in text:
frequency[char] = frequency.get(char, 0) + 1
for char, count in frequency.items():
if count > 1:
duplicates.append(char)
return duplicates
Binary Trees
1. How can all leaf nodes of a binary tree be printed?
A leaf is a node that has neither a left child nor a right child. A recursive traversal can visit every node and print values that satisfy this condition.
def print_leaves(root):
if root:
if root.left is None and root.right is None:
print(root.value)
print_leaves(root.left)
print_leaves(root.right)
2. How do you determine whether a tree is a Binary Search Tree?
Each node must remain within a valid minimum and maximum range. During recursion, the permitted range is updated according to the current node’s value.
def is_bst(node, low=float('-inf'), high=float('inf')):
if node is None:
return True
if not (low < node.value < high):
return False
return (
is_bst(node.left, low, node.value)
and is_bst(node.right, node.value, high)
)
3. How is a Binary Search Tree implemented?
A basic BST supports operations such as inserting values and searching for a particular value. Smaller values are placed on the left, while larger values are directed to the right.
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left:
self.left.insert(value)
else:
self.left = BSTNode(value)
else:
if self.right:
self.right.insert(value)
else:
self.right = BSTNode(value)
def search(self, value):
if value < self.value:
return self.left.search(value) if self.left else False
if value > self.value:
return self.right.search(value) if self.right else False
return True
4. How do you find the Lowest Common Ancestor?
For a general binary tree, recursively search both branches. If one target appears in each branch, the current node is the common ancestor. Otherwise, return the branch that contains a target.
def lowest_common_ancestor(root, p, q):
if root is None or root == p or root == q:
return root
left = lowest_common_ancestor(root.left, p, q)
right = lowest_common_ancestor(root.right, p, q)
if left and right:
return root
return left if left else right
Graphs
1. How can a cycle be detected in a directed graph?
Depth-First Search can be combined with a recursion-stack marker. If DFS reaches a node that is already present in the current recursion path, a cycle exists.
def has_cycle(graph):
visited = [False] * len(graph)
active = [False] * len(graph)
def dfs(node):
visited[node] = True
active[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
if dfs(neighbor):
return True
elif active[neighbor]:
return True
active[node] = False
return False
for node in range(len(graph)):
if not visited[node] and dfs(node):
return True
return False
2. How do you detect a cycle in an undirected graph?
During DFS, keep track of the node from which the current node was reached. Finding an already visited neighbor that is not the parent indicates a cycle.
def has_cycle_undirected(graph):
visited = [False] * len(graph)
def dfs(node, parent):
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
if dfs(neighbor, node):
return True
elif neighbor != parent:
return True
return False
for node in range(len(graph)):
if not visited[node] and dfs(node, -1):
return True
return False
3. How can strongly connected components be found?
For a directed graph, algorithms such as Kosaraju’s and Tarjan’s can identify strongly connected components. Kosaraju’s approach uses DFS ordering and the transpose of the graph.
4. How can you check whether a path exists between two graph nodes?
Run DFS or BFS from the starting node. If the destination is reached during traversal, a path exists; otherwise, it does not.
def path_exists(graph, start, end):
visited = [False] * len(graph)
def dfs(node):
if node == end:
return True
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor] and dfs(neighbor):
return True
return False
return dfs(start)
5. How can the minimum number of swaps needed to sort an array be calculated?
Compare the current arrangement with its sorted arrangement and treat misplaced positions as cycles. A cycle containing k elements requires k - 1 swaps.
def min_swaps(arr):
n = len(arr)
indexed = list(enumerate(arr))
indexed.sort(key=lambda item: item[1])
visited = [False] * n
swaps = 0
for i in range(n):
if visited[i] or indexed[i][0] == i:
continue
cycle_size = 0
j = i
while not visited[j]:
visited[j] = True
j = indexed[j][0]
cycle_size += 1
swaps += cycle_size - 1
return swaps
Dynamic Programming
1. How do you find the Longest Common Subsequence?
Dynamic programming can compare prefixes of two sequences. When matching characters are found, the previous diagonal value is extended; otherwise, the larger value from the neighboring states is retained.
def lcs(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
2. How do you find the Longest Common Substring?
Unlike a subsequence, a common substring must remain continuous. The dynamic programming table therefore resets the current length whenever the compared characters do not match.
def longest_common_substring(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
longest = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
longest = max(longest, dp[i][j])
return longest
3. How is the Coin Change problem solved?
Create a dynamic programming array where each position represents the smallest number of coins required to form that amount. Update the values using each available denomination.
def coin_change(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for value in range(coin, amount + 1):
dp[value] = min(dp[value], dp[value - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
4. How can the Box Stacking problem be solved?
The problem can be treated as a dynamic programming task. Generate possible orientations, arrange them by base area, and calculate the greatest stack height while ensuring that each box placed above another has a smaller base.
class Box:
def __init__(self, height, width, depth):
self.height = height
self.width = width
self.depth = depth
5. How can the number of ways to cover a distance be calculated?
If a person can move one, two, or three steps at a time, the number of possibilities for a distance depends on the results of the previous three distances.
def count_ways(n):
if n == 0:
return 1
ways = [0] * (n + 1)
ways[0] = 1
if n >= 1:
ways[1] = 1
if n >= 2:
ways[2] = 2
for i in range(3, n + 1):
ways[i] = ways[i - 1] + ways[i - 2] + ways[i - 3]
return ways[n]
Quick Preparation Tips
- Practice writing solutions without depending completely on an IDE.
- Understand the logic behind an algorithm instead of memorizing code.
- Pay attention to time and space complexity.
- Practice explaining your approach before writing the final solution.
- Revise arrays, linked lists, strings, trees, graphs, and dynamic programming regularly.
Complete Advance AI Topics: Click Here
SQL Tutorial: Click Here
Frequently Asked Questions
Which topics should I prepare for programming interviews?
Arrays, linked lists, strings, trees, graphs, algorithms, and dynamic programming are important areas for coding interview preparation.
Is Python suitable for coding interviews?
Yes. Python provides concise syntax and useful built-in data structures, making it convenient for solving many algorithmic problems.
Should I learn the algorithm or memorize the code?
Understanding the algorithm is more useful. Once the logic is clear, implementing the solution in code becomes easier.
Why are data structures important in interviews?
Data structures help organize and process information efficiently. Interview questions often use them to evaluate logical thinking and algorithmic skills.
Final Thoughts
Programming interview preparation becomes easier when you practice problems from different data-structure and algorithm categories. The questions covered here provide a useful starting point for arrays, linked lists, strings, binary trees, graphs, and dynamic programming. Focus on understanding the reasoning behind each solution, analyze its complexity, and practice implementing similar problems independently.
Keywords: programming interview questions, coding interview questions, programming interview questions and answers, coding questions for freshers, Python coding interview questions, data structures interview questions, algorithms interview questions, technical interview preparation,programming interview questions programming interview questions and answers coding interview questions coding interview questions for freshers Python coding interview questions data structures interview questions algorithms interview questions technical interview questions programming questions for interviews coding questions for freshers DSA interview questions array interview questions linked list interview questions string interview questions binary tree interview questions graph interview questions dynamic programming interview questions programming interview preparation coding interview preparation technical interview preparation programming questions and answers common programming interview questions important coding interview questions