Coding Prep9 September 2026β€’20 min readβ€’1,879 words

Top 15 Python Coding Questions for Technical Interviews (With Solutions)

Comprehensive collection of the top 20 Python coding problems tested in technical interviews. Complete code solutions, explanations, time complexity analysis, and Pythonic patterns.

Abu Thahir

Abu Thahir

Founder & Career Mentor at GetJobWithAbu

Python has become the preferred language for coding rounds at tech companies due to its clean syntax and powerful standard library. However, interviewers do not just look for code that passes; they evaluate whether you write idiomatic, efficient Python and understand time and space complexity.

Here are the most frequently asked Python coding questions with complete explanations, optimal solutions, and common edge cases.

---

1. Two Sum Problem

Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

```python

def two_sum(nums: list[int], target: int) -> list[int]:

seen = {} # value -> index

for i, num in enumerate(nums):

complement = target - num

if complement in seen:

return [seen[complement], i]

seen[num] = i

return []

print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]

```

  • Time Complexity: O(N) β€” Single pass hash map lookup.
  • Space Complexity: O(N) β€” Storing elements in dictionary.
  • Key Edge Case: Duplicate values in nums (e.g., [3, 3] with target 6). The complement check must precede the dictionary insertion.

---

2. Valid Anagram

Problem: Given two strings s and t, return True if t is an anagram of s, and False otherwise.

```python

from collections import Counter

def is_anagram(s: str, t: str) -> bool:

if len(s) != len(t):

return False

return Counter(s) == Counter(t)

print(is_anagram("anagram", "nagaram")) # True

print(is_anagram("rat", "car")) # False

```

  • Time Complexity: O(N) β€” Linear pass to count frequencies.
  • Space Complexity: O(1) β€” The character set is bounded (26 lowercase English letters).

---

3. Reverse Words in a String

Problem: Given an input string s, reverse the order of the words while trimming leading, trailing, and multiple intervening spaces.

```python

def reverse_words(s: str) -> str:

words = s.split()

return " ".join(words[::-1])

print(reverse_words(" the sky is blue ")) # "blue is sky the"

```

  • Time Complexity: O(N)
  • Space Complexity: O(N) to store extracted words.

---

4. Find the First Non-Repeating Character

Problem: Return the index of the first non-repeating character in a string. If it does not exist, return -1.

```python

from collections import Counter

def first_uniq_char(s: str) -> int:

count = Counter(s)

for idx, char in enumerate(s):

if count[char] == 1:

return idx

return -1

print(first_uniq_char("leetcode")) # 0 ('l')

print(first_uniq_char("loveleetcode")) # 2 ('v')

```

  • Time Complexity: O(N) β€” Two linear passes (one to count frequencies, one to find index).
  • Space Complexity: O(1) β€” Maximum 26 distinct keys in hash map.

---

5. Group Anagrams

Problem: Given an array of strings strs, group the anagrams together.

```python

from collections import defaultdict

def group_anagrams(strs: list[str]) -> list[list[str]]:

anagram_map = defaultdict(list)

for word in strs:

key = tuple(sorted(word))

anagram_map[key].append(word)

return list(anagram_map.values())

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

```

  • Time Complexity: O(N * K log K), where N is number of strings and K is the maximum length of a string.
  • Space Complexity: O(N * K) to store grouped lists.

---

6. Merge Two Sorted Lists

Problem: Merge two sorted linked lists into one sorted linked list.

```python

class ListNode:

def __init__(self, val=0, next=None):

self.val = val

self.next = next

def merge_two_lists(l1: ListNode, l2: ListNode) -> ListNode:

dummy = ListNode(-1)

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 if l1 else l2

return dummy.next

```

  • Time Complexity: O(N + M) where N and M are the lengths of the two lists.
  • Space Complexity: O(1) β€” Pointers are mutated in place without allocating new nodes.

---

7. Longest Substring Without Repeating Characters

Problem: Given a string s, find the length of the longest substring without repeating characters.

```python

def length_of_longest_substring(s: str) -> int:

char_map = {}

left = 0

max_len = 0

for right, char in enumerate(s):

if char in char_map and char_map[char] >= left:

left = char_map[char] + 1

char_map[char] = right

max_len = max(max_len, right - left + 1)

return max_len

print(length_of_longest_substring("abcabcbb")) # 3 ("abc")

```

  • Time Complexity: O(N) β€” Sliding window where left and right iterate at most N times.
  • Space Complexity: O(min(N, M)) where M is the charset size.

---

8. Maximum Subarray Sum (Kadane's Algorithm)

Problem: Given an integer array nums, find the subarray with the largest sum, and return its sum.

```python

def max_sub_array(nums: list[int]) -> int:

if not nums:

return 0

current_sum = nums[0]

max_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

print(max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # Output: 6 ([4, -1, 2, 1])

```

  • Time Complexity: O(N) β€” Single pass through the array.
  • Space Complexity: O(1) β€” Constant memory using two tracking scalar variables.
  • Key Edge Case: When all numbers are negative (e.g. [-5, -2, -8]), the algorithm returns -2 rather than 0 because max_sum is initialized to nums[0].

---

9. Valid Parentheses Using a Stack

Problem: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

```python

def is_valid_parentheses(s: str) -> bool:

if len(s) % 2 != 0:

return False

bracket_map = {')': '(', '}': '{', ']': '['}

stack = []

for char in s:

if char in bracket_map:

top = stack.pop() if stack else '#'

if bracket_map[char] != top:

return False

else:

stack.append(char)

return len(stack) == 0

print(is_valid_parentheses("()[]{}")) # True

print(is_valid_parentheses("(]")) # False

```

  • Time Complexity: O(N) β€” Single pass through characters.
  • Space Complexity: O(N) β€” Worst case all opening brackets pushed to stack.

---

10. Merge Overlapping Intervals

Problem: Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals.

```python

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:

if not intervals:

return []

intervals.sort(key=lambda x: x[0])

merged = [intervals[0]]

for current in intervals[1:]:

last_merged = merged[-1]

if current[0] <= last_merged[1]:

last_merged[1] = max(last_merged[1], current[1])

else:

merged.append(current)

return merged

print(merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]))

```

  • Time Complexity: O(N log N) dominated by sorting.
  • Space Complexity: O(N) to hold merged result.

---

11. Top K Frequent Elements

Problem: Given an integer array nums and an integer k, return the k most frequent elements.

```python

import heapq

from collections import Counter

def top_k_frequent(nums: list[int], k: int) -> list[int]:

count = Counter(nums)

return [item[0] for item in count.most_common(k)]

def top_k_frequent_heap(nums: list[int], k: int) -> list[int]:

count = Counter(nums)

heap = []

for num, freq in count.items():

heapq.heappush(heap, (freq, num))

if len(heap) > k:

heapq.heappop(heap)

return [num for freq, num in heap]

print(top_k_frequent([1, 1, 1, 2, 2, 3], 2)) # Output: [1, 2]

```

  • Time Complexity: O(N log k) using a min-heap of size k.
  • Space Complexity: O(N) to store frequency map.

---

12. Search in Rotated Sorted Array

Problem: Given array nums sorted in ascending order and rotated at an unknown pivot, find the index of target in O(log N) time.

```python

def search_rotated(nums: list[int], target: int) -> int:

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

print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0)) # Output: 4

```

  • Time Complexity: O(log N) β€” Modified binary search.
  • Space Complexity: O(1) β€” In-place pointer manipulation.

---

13. Subarray Sum Equals K

Problem: Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals k.

```python

from collections import defaultdict

def subarray_sum(nums: list[int], k: int) -> int:

prefix_counts = defaultdict(int)

prefix_counts[0] = 1 # Base case: a prefix sum that exactly equals k

current_sum = 0

total_count = 0

for num in nums:

current_sum += num

total_count += prefix_counts[current_sum - k]

prefix_counts[current_sum] += 1

return total_count

print(subarray_sum([1, 1, 1], 2)) # Output: 2

print(subarray_sum([1, 2, 3], 3)) # Output: 2 ([1, 2] and [3])

```

  • Time Complexity: O(N) β€” Single pass with hash table lookups.
  • Space Complexity: O(N) to store distinct prefix sum frequencies.
  • Why Naive O(N^2) Fails: Two nested loops will hit Time Limit Exceeded (TLE) when array length reaches 20,000+.

---

14. Detect Cycle in a Linked List (Floyd's Tortoise and Hare)

Problem: Given the head of a linked list, determine if the list has a cycle in O(1) memory.

```python

class ListNode:

def __init__(self, val=0, next=None):

self.val = val

self.next = next

def has_cycle(head: ListNode) -> bool:

if not head or not head.next:

return False

slow = head

fast = head

while fast and fast.next:

slow = slow.next

fast = fast.next.next

if slow == fast:

return True

return False

```

  • Time Complexity: O(N) β€” The fast pointer completes at most two laps within the cycle before intercepting the slow pointer.
  • Space Complexity: O(1) β€” No hash set or additional node storage.

---

15. Trapping Rain Water (Two Pointers)

Problem: Given n non-negative integers representing an elevation map where width of each bar is 1, compute how much water it can trap after raining.

```python

def trap_water(height: list[int]) -> int:

if not height:

return 0

left, right = 0, len(height) - 1

left_max, right_max = height[left], height[right]

trapped_water = 0

while left < right:

if left_max < right_max:

left += 1

left_max = max(left_max, height[left])

trapped_water += left_max - height[left]

else:

right -= 1

right_max = max(right_max, height[right])

trapped_water += right_max - height[right]

return trapped_water

print(trap_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) # Output: 6

```

  • Time Complexity: O(N) β€” Single pass inward from both array boundaries.
  • Space Complexity: O(1) β€” Replaces standard O(N) dynamic programming arrays with two running scalar maximums.

---

16. Python Idioms That Impress Technical Interviewers

When coding in Python during an interview, leverage built-in language features rather than re-inventing basic primitives:

  1. List Comprehensions with Conditions: Use [x**2 for x in nums if x % 2 == 0] instead of verbose 4-line initialization loops.
  2. `enumerate(iterable, start=0)`: Never write range(len(arr)) when you need both the index and the element.
  3. `zip(*matrix)`: Transposes a 2D matrix in a single readable line.
  4. `collections.defaultdict`: Avoids repetitive if key not in dict: guards when accumulating groupings.
  5. `collections.Counter`: Enables instant O(N) frequency histograms with built-in multiset subtraction.

---

17. Practical Engineering Interview Checklist

Before declaring your code ready to run during a live coding interview:

  • [ ] Clarify Input Constraints: Ask the interviewer whether numbers can be negative, whether strings can contain whitespace/symbols, and what maximum input size to expect.
  • [ ] Trace Edge Cases Manually: Test empty inputs ([] or ""), single-element arrays, already sorted arrays, and identical duplicates before executing.
  • [ ] State Big-O Complexity Proactively: State both time and auxiliary space complexity before the interviewer asks.
  • [ ] Think Aloud: Explain your algorithmic trade-offs (e.g. trading O(N) memory via a hash map to achieve O(1) lookup time) so the interviewer evaluates your engineering reasoning even if a syntax error occurs.
Abu - Founder of GetJobWithAbu

Abu

Founder of GetJobWithAbuCloud & Azure Developer (5+ Years IT Exp)

Cloud & Azure Developer with 5+ years of IT industry experience, having transitioned from a 4.8-year IT Support role into Software & Cloud Development. Dedicated to helping freshers, Tier-2/Tier-3 college graduates, and IT support engineers crack technical interviews through practical production insights, real-world scenario questions, and hands-on guidance.

πŸ“… Last updated: Read Abu's Full Story & Verification Principles β†’
πŸ“š Recommended Technical Prep

Related Technical Guides & Interview Prep

View All 15+ Guides β†’

Related Articles