Top 50 Repeated Coding Interview Questions
BY SYNTAX ERROR - Instagram: @code.abhii07
Array & String Problems
BY SYNTAX ERROR
1. Two Sum
Problem: Find two numbers in array that add up to target
python
def two_sum(nums, target):
hash_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hash_map:
return [hash_map[complement], i]
hash_map[num] = i
# BY SYNTAX ERROR
2. Reverse String
Problem: Reverse a string in-place
python
def reverse_string(s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# BY SYNTAX ERROR
3. Valid Palindrome
Problem: Check if string is palindrome ignoring case and non-alphanumeric
python
def is_palindrome(s):
s = ''.join(c.lower() for c in s if c.isalnum())
return s == s[::-1]
# BY SYNTAX ERROR
4. Maximum Subarray (Kadane's Algorithm)
Problem: Find contiguous subarray with largest sum
python
def max_subarray(nums):
max_sum = current_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# BY SYNTAX ERROR
5. Contains Duplicate
Problem: Check if array contains duplicates
python
def contains_duplicate(nums):
return len(nums) != len(set(nums))
# BY SYNTAX ERROR
6. Product of Array Except Self
Problem: Return array where each element is product of all others
python
def product_except_self(nums):
result = [1] * len(nums)
for i in range(1, len(nums)):
result[i] = result[i-1] * nums[i-1]
right = 1
for i in range(len(nums)-1, -1, -1):
result[i] *= right
right *= nums[i]
return result
# BY SYNTAX ERROR
7. Move Zeros
Problem: Move all zeros to end while maintaining order
python
def move_zeros(nums):
write_index = 0
for read_index in range(len(nums)):
if nums[read_index] != 0:
nums[write_index] = nums[read_index]
write_index += 1
while write_index < len(nums):
nums[write_index] = 0
write_index += 1
# BY SYNTAX ERROR
8. Best Time to Buy and Sell Stock
Problem: Find maximum profit from buying and selling stock once
python
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
# BY SYNTAX ERROR
9. Valid Anagram
Problem: Check if two strings are anagrams
python
def is_anagram(s, t):
return sorted(s) == sorted(t)
# BY SYNTAX ERROR
10. Longest Substring Without Repeating Characters
Problem: Find length of longest substring without repeating characters
python
def length_of_longest_substring(s):
char_set = set()
left = max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
# BY SYNTAX ERROR
Linked List Problems
BY SYNTAX ERROR
11. Reverse Linked List
Problem: Reverse a singly linked list
python
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# BY SYNTAX ERROR
12. Merge Two Sorted Lists
Problem: Merge two sorted linked lists
python
def merge_two_lists(l1, l2):
dummy = ListNode(0)
current = dummy
while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 or l2
return dummy.next
# BY SYNTAX ERROR
13. Remove Nth Node From End
Problem: Remove nth node from end of linked list
python
def remove_nth_from_end(head, n):
dummy = ListNode(0)
dummy.next = head
first = second = dummy
for _ in range(n + 1):
first = first.next
while first:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next
# BY SYNTAX ERROR
14. Linked List Cycle
Problem: Detect if linked list has cycle
python
def has_cycle(head):
if not head or not head.next:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# BY SYNTAX ERROR
15. Middle of Linked List
Problem: Find middle node of linked list
python
def middle_node(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# BY SYNTAX ERROR
Binary Tree Problems
BY SYNTAX ERROR
16. Maximum Depth of Binary Tree
Problem: Find maximum depth of binary tree
python
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
# BY SYNTAX ERROR
17. Binary Tree Inorder Traversal
Problem: Traverse binary tree inorder
python
def inorder_traversal(root):
result = []
def inorder(node):
if node:
inorder(node.left)
result.append(node.val)
inorder(node.right)
inorder(root)
return result
# BY SYNTAX ERROR
18. Same Tree
Problem: Check if two binary trees are identical
python
def is_same_tree(p, q):
if not p and not q:
return True
if not p or not q:
return False
return (p.val == q.val and
is_same_tree(p.left, q.left) and
is_same_tree(p.right, q.right))
# BY SYNTAX ERROR
19. Symmetric Tree
Problem: Check if binary tree is symmetric
python
def is_symmetric(root):
def is_mirror(left, right):
if not left and not right:
return True
if not left or not right:
return False
return (left.val == right.val and
is_mirror(left.left, right.right) and
is_mirror(left.right, right.left))
return is_mirror(root, root)
# BY SYNTAX ERROR
20. Binary Tree Level Order Traversal
Problem: Traverse binary tree level by level
python
def level_order(root):
if not root:
return []
result, queue = [], [root]
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
# BY SYNTAX ERROR
Dynamic Programming
BY SYNTAX ERROR
21. Climbing Stairs
Problem: Count ways to climb n stairs (1 or 2 steps at a time)
python
def climb_stairs(n):
if n <= 2:
return n
prev2, prev1 = 1, 2
for i in range(3, n + 1):
current = prev1 + prev2
prev2, prev1 = prev1, current
return prev1
# BY SYNTAX ERROR
22. House Robber
Problem: Maximum money robbed without robbing adjacent houses
python
def rob(nums):
if not nums:
return 0
if len(nums) == 1:
return nums[0]
dp = [0] * len(nums)
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
return dp[-1]
# BY SYNTAX ERROR
23. Coin Change
Problem: Minimum coins needed to make amount
python
def coin_change(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
# BY SYNTAX ERROR
24. Longest Increasing Subsequence
Problem: Find length of longest increasing subsequence
python
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
# BY SYNTAX ERROR
25. Unique Paths
Problem: Count unique paths from top-left to bottom-right
python
def unique_paths(m, n):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
# BY SYNTAX ERROR
Searching & Sorting
BY SYNTAX ERROR
26. Binary Search
Problem: Find target in sorted array
python
def binary_search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# BY SYNTAX ERROR
27. Find First and Last Position
Problem: Find first and last occurrence of target
python
def search_range(nums, target):
def find_first():
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] >= target:
right = mid - 1
else:
left = mid + 1
return left
first = find_first()
if first == len(nums) or nums[first] != target:
return [-1, -1]
def find_last():
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid - 1
return right
return [first, find_last()]
# BY SYNTAX ERROR
28. Merge Intervals
Problem: Merge overlapping intervals
python
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
if current[0] <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], current[1])
else:
merged.append(current)
return merged
# BY SYNTAX ERROR
29. Search in Rotated Sorted Array
Problem: Search target in rotated sorted array
python
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
# BY SYNTAX ERROR
30. Kth Largest Element
Problem: Find kth largest element in array
python
import heapq
def find_kth_largest(nums, k):
return heapq.nlargest(k, nums)[-1]
# BY SYNTAX ERROR
Stack & Queue
BY SYNTAX ERROR
31. Valid Parentheses
Problem: Check if parentheses are balanced
python
def is_valid(s):
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
if not stack or stack.pop() != mapping[char]:
return False
else:
stack.append(char)
return not stack
# BY SYNTAX ERROR
32. Min Stack
Problem: Stack with min operation in O(1)
python
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val):
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self):
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self):
return self.stack[-1]
def getMin(self):
return self.min_stack[-1]
# BY SYNTAX ERROR
33. Evaluate Reverse Polish Notation
Problem: Evaluate expression in postfix notation
python
def eval_rpn(tokens):
stack = []
operators = {'+', '-', '*', '/'}
for token in tokens:
if token in operators:
b, a = stack.pop(), stack.pop()
if token == '+':
stack.append(a + b)
elif token == '-':
stack.append(a - b)
elif token == '*':
stack.append(a * b)
else:
stack.append(int(a / b))
else:
stack.append(int(token))
return stack[0]
# BY SYNTAX ERROR
34. Daily Temperatures
Problem: Find next warmer temperature for each day
python
def daily_temperatures(temperatures):
result = [0] * len(temperatures)
stack = []
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result
# BY SYNTAX ERROR
35. Implement Queue using Stacks
Problem: Implement queue using two stacks
python
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x):
self.stack1.append(x)
def pop(self):
self.peek()
return self.stack2.pop()
def peek(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def empty(self):
return not self.stack1 and not self.stack2
# BY SYNTAX ERROR
Graph Problems
BY SYNTAX ERROR
36. Number of Islands
Problem: Count number of islands in 2D grid
python
def num_islands(grid):
if not grid:
return 0
def dfs(i, j):
if (i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or
grid[i][j] != '1'):
return
grid[i][j] = '0'
dfs(i+1, j)
dfs(i-1, j)
dfs(i, j+1)
dfs(i, j-1)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i, j)
count += 1
return count
# BY SYNTAX ERROR
37. Clone Graph
Problem: Clone undirected graph
python
def clone_graph(node):
if not node:
return None
visited = {}
def dfs(node):
if node in visited:
return visited[node]
clone = Node(node.val)
visited[node] = clone
for neighbor in node.neighbors:
clone.neighbors.append(dfs(neighbor))
return clone
return dfs(node)
# BY SYNTAX ERROR
38. Course Schedule
Problem: Check if all courses can be finished (cycle detection)
python
def can_finish(numCourses, prerequisites):
graph = [[] for _ in range(numCourses)]
for course, prereq in prerequisites:
graph[prereq].append(course)
WHITE, GRAY, BLACK = 0, 1, 2
color = [WHITE] * numCourses
def dfs(node):
if color[node] == GRAY:
return False
if color[node] == BLACK:
return True
color[node] = GRAY
for neighbor in graph[node]:
if not dfs(neighbor):
return False
color[node] = BLACK
return True
for i in range(numCourses):
if not dfs(i):
return False
return True
# BY SYNTAX ERROR
39. Pacific Atlantic Water Flow
Problem: Find cells where water can flow to both oceans
python
def pacific_atlantic(heights):
if not heights:
return []
m, n = len(heights), len(heights[0])
pacific = [[False] * n for _ in range(m)]
atlantic = [[False] * n for _ in range(m)]
def dfs(i, j, ocean):
ocean[i][j] = True
for di, dj in [(0,1), (0,-1), (1,0), (-1,0)]:
ni, nj = i + di, j + dj
if (0 <= ni < m and 0 <= nj < n and
not ocean[ni][nj] and heights[ni][nj] >= heights[i][j]):
dfs(ni, nj, ocean)
for i in range(m):
dfs(i, 0, pacific)
dfs(i, n-1, atlantic)
for j in range(n):
dfs(0, j, pacific)
dfs(m-1, j, atlantic)
result = []
for i in range(m):
for j in range(n):
if pacific[i][j] and atlantic[i][j]:
result.append([i, j])
return result
# BY SYNTAX ERROR
40. Word Ladder
Problem: Find shortest transformation sequence
python
from collections import deque
def ladder_length(beginWord, endWord, wordList):
if endWord not in wordList:
return 0
wordList = set(wordList)
queue = deque([(beginWord, 1)])
while queue:
word, length = queue.popleft()
if word == endWord:
return length
for i in range(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
new_word = word[:i] + c + word[i+1:]
if new_word in wordList:
wordList.remove(new_word)
queue.append((new_word, length + 1))
return 0
# BY SYNTAX ERROR
Backtracking
BY SYNTAX ERROR
41. Generate Parentheses
Problem: Generate all valid parentheses combinations
python
def generate_parenthesis(n):
result = []
def backtrack(current, open_count, close_count):
if len(current) == 2 * n:
result.append(current)
return
if open_count < n:
backtrack(current + '(', open_count + 1, close_count)
if close_count < open_count:
backtrack(current + ')', open_count, close_count + 1)
backtrack('', 0, 0)
return result
# BY SYNTAX ERROR
42. Letter Combinations of Phone Number
Problem: Generate all letter combinations from phone number
python
def letter_combinations(digits):
if not digits:
return []
mapping = {
'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
result = []
def backtrack(index, current):
if index == len(digits):
result.append(current)
return
for letter in mapping[digits[index]]:
backtrack(index + 1, current + letter)
backtrack(0, '')
return result
# BY SYNTAX ERROR
43. Subsets
Problem: Generate all possible subsets
python
def subsets(nums):
result = []
def backtrack(start, current):
result.append(current[:])
for i in range(start, len(nums)):
current.append(nums[i])
backtrack(i + 1, current)
current.pop()
backtrack(0, [])
return result
# BY SYNTAX ERROR
44. Permutations
Problem: Generate all permutations of array
python
def permute(nums):
result = []
def backtrack(current):
if len(current) == len(nums):
result.append(current[:])
return
for num in nums:
if num not in current:
current.append(num)
backtrack(current)
current.pop()
backtrack([])
return result
# BY SYNTAX ERROR
45. Combination Sum
Problem: Find all combinations that sum to target
python
def combination_sum(candidates, target):
result = []
def backtrack(start, current, remaining):
if remaining == 0:
result.append(current[:])
return
for i in range(start, len(candidates)):
if candidates[i] <= remaining:
current.append(candidates[i])
backtrack(i, current, remaining - candidates[i])
current.pop()
backtrack(0, [], target)
return result
# BY SYNTAX ERROR
Hash Table & Design
BY SYNTAX ERROR
46. Group Anagrams
Problem: Group anagrams together
python
def group_anagrams(strs):
from collections import defaultdict
groups = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
groups[key].append(s)
return list(groups.values())
# BY SYNTAX ERROR
47. Top K Frequent Elements
Problem: Find k most frequent elements
python
def top_k_frequent(nums, k):
from collections import Counter
import heapq
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
# BY SYNTAX ERROR
48. Longest Consecutive Sequence
Problem: Find longest consecutive sequence length
python
def longest_consecutive(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_length = 1
while current_num + 1 in num_set:
current_num += 1
current_length += 1
longest = max(longest, current_length)
return longest
# BY SYNTAX ERROR
49. LRU Cache
Problem: Implement LRU cache
python
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.order = []
def get(self, key):
if key in self.cache:
self.order.remove(key)
self.order.append(key)
return self.cache[key]
return -1
def put(self, key, value):
if key in self.cache:
self.order.remove(key)
elif len(self.cache) >= self.capacity:
oldest = self.order.pop(0)
del self.cache[oldest]
self.cache[key] = value
self.order.append(key)
# BY SYNTAX ERROR
50. Design Twitter
Problem: Design simplified Twitter
python
class Twitter:
def __init__(self):
self.tweets = []
self.following = {}
def postTweet(self, userId, tweetId):
self.tweets.append((userId, tweetId))
def getNewsFeed(self, userId):
following_set = self.following.get(userId, set())
following_set.add(userId)
feed = []
for user, tweet in reversed(self.tweets):
if user in following_set:
feed.append(tweet)
if len(feed) == 10:
break
return feed
def follow(self, followerId, followeeId):
if followerId not in self.following:
self.following[followerId] = set()
self.following[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
if followerId in self.following:
self.following[followerId].discard(followeeId)
# BY SYNTAX ERROR
Common Syntax Errors to Avoid
BY SYNTAX ERROR
Python Syntax Errors:
1. Indentation Error: Use consistent 4 spaces
2. Missing Colons: After if, for, while, def, class
3. Parentheses Mismatch: Always balance ()
4. Variable Naming: Use snake_case, not camelCase
5. List Index: Remember 0-based indexing
6. Dictionary Access: Use .get() for safe access
7. String Concatenation: Use f-strings or .format()
8. Boolean Values: Use True/False, not true/false
9. Range Function: range(n) goes from 0 to n-1
10. Return Statement: Don't forget to return values
Common Logic Errors:
1. Off-by-one errors in loops and array bounds
2. Infinite loops without proper exit conditions
3. Null pointer exceptions - always check for None
4. Integer overflow in some languages
5. Incorrect base cases in recursion
6. Modifying collection while iterating
7. Incorrect comparison operators (== vs =)
8. Scope issues with variables
9. Incorrect time/space complexity assumptions
10. Edge case handling - empty inputs, single elements
Tips for Success - BY SYNTAX ERROR:
Always test with edge cases
Trace through your code with sample inputs
Consider time and space complexity