Coding Test Practice
Interview Zone: Coding Test Practice Preparation
Top 30+ Coding Test Practice Interview Questions for Freshers
Coding tests are an essential part of many technical interviews. Preparing well for coding test practice interview questions for freshers can greatly improve your chances of success. These coding challenges evaluate your problem-solving skills, algorithm knowledge, and coding efficiency. This guide provides over 30 carefully selected questions that range from easy to advanced levels, complete with detailed Python solutions to help you learn effectively.
By regularly practicing these coding test practice interview questions for freshers, you will develop stronger logical thinking and coding fluency. Additionally, you will learn to optimize your code and debug errors, which are crucial skills during timed coding tests.
Basic Coding Questions for Freshers
1. Reverse a string
Write a program to reverse a given string. For example, input: “hello”, output: “olleh”.
def reverse_string(s): return s[::-1] # Example usage print(reverse_string("hello")) # Output: olleh
2. Check if a number is even or odd
Determine if an integer is even or odd.
def is_even(num): return num % 2 == 0 # Example usage print(is_even(4)) # Output: True (Even) print(is_even(7)) # Output: False (Odd)
3. Find the maximum number in an array
Given an array, return the largest element.
def find_max(arr): max_val = arr[0] for num in arr: if num > max_val: max_val = num return max_val # Example usage print(find_max([3, 5, 1, 9, 2])) # Output: 9
4. Print Fibonacci series up to n terms
Generate the Fibonacci sequence up to n terms.
def fibonacci(n): fib = [0, 1] for i in range(2, n): fib.append(fib[i-1] + fib[i-2]) return fib[:n] # Example usage print(fibonacci(7)) # Output: [0, 1, 1, 2, 3, 5, 8]
5. Check if a string is a palindrome
Determine whether a string reads the same backward as forward.
def is_palindrome(s): return s == s[::-1] # Example usage print(is_palindrome("racecar")) # Output: True print(is_palindrome("hello")) # Output: False
6. Find factorial of a number
Calculate n! (product of all positive integers up to n).
def factorial(n): if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i return result # Example usage print(factorial(5)) # Output: 120
7. Count vowels in a string
Count how many vowels (a, e, i, o, u) appear in a string.
def count_vowels(s): vowels = "aeiouAEIOU" count = 0 for char in s: if char in vowels: count += 1 return count # Example usage print(count_vowels("Interview Zone")) # Output: 5
8. Swap two numbers without a temporary variable
Swap the values of two variables without using extra space.
def swap(a, b): a = a + b b = a - b a = a - b return a, b # Example usage x, y = swap(5, 10) print(x, y) # Output: 10 5
9. Check prime number
Determine if a number is prime.
def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True # Example usage print(is_prime(11)) # Output: True print(is_prime(15)) # Output: False
10. Find the sum of digits of a number
Calculate the sum of all digits in a given integer.
def sum_of_digits(num): total = 0 while num > 0: total += num % 10 num //= 10 return total # Example usage print(sum_of_digits(1234)) # Output: 10
Medium Coding Test Practice Questions
11. Find the first non-repeating character in a string
def first_non_repeating_char(s): char_count = {} # Count the frequency of each character for char in s: char_count[char] = char_count.get(char, 0) + 1 # Find the first character with count 1 for char in s: if char_count[char] == 1: return char return None # Example usage print(first_non_repeating_char("interview")) # Output: 'n'
12. Merge two sorted arrays
def merge_sorted_arrays(arr1, arr2): i = j = 0 merged = [] # Compare elements from both arrays and append the smaller one while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: merged.append(arr1[i]) i += 1 else: merged.append(arr2[j]) j += 1 # Append remaining elements merged.extend(arr1[i:]) merged.extend(arr2[j:]) return merged # Example usage print(merge_sorted_arrays([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]
13. Find the missing number in an array of size n with numbers 1 to n+1
def find_missing_number(arr, n): expected_sum = (n + 1) * (n + 2) // 2 # Sum of 1 to n+1 actual_sum = sum(arr) return expected_sum - actual_sum # Example usage print(find_missing_number([1, 2, 4, 5, 6], 5)) # Output: 3
14. Implement binary search
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1 # Example usage print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
15. Reverse words in a sentence
def reverse_words(sentence): words = sentence.split() return " ".join(words[::-1]) # Example usage print(reverse_words("Interview Zone is great")) # Output: "great is Zone Interview"
16. Check if two strings are anagrams
def are_anagrams(s1, s2): return sorted(s1) == sorted(s2) # Example usage print(are_anagrams("listen", "silent")) # Output: True print(are_anagrams("hello", "world")) # Output: False
17. Remove duplicates from an array
def remove_duplicates(arr): return list(set(arr)) # Example usage print(remove_duplicates([1, 2, 2, 3, 4, 4])) # Output: [1, 2, 3, 4]
18. Find the longest substring without repeating characters
def longest_unique_substring(s): chars = set() left = max_len = 0 for right in range(len(s)): while s[right] in chars: chars.remove(s[left]) left += 1 chars.add(s[right]) max_len = max(max_len, right - left + 1) return max_len # Example usage print(longest_unique_substring("abcabcbb")) # Output: 3
19. Find pairs in array that sum to a target
def find_pairs(arr, target): seen = set() pairs = [] for num in arr: complement = target - num if complement in seen: pairs.append((complement, num)) seen.add(num) return pairs # Example usage print(find_pairs([1, 2, 3, 4, 5], 6)) # Output: [(2, 4), (1, 5)]
20. Implement a queue using stacks
class QueueUsingStacks: def __init__(self): self.stack1 = [] # For enqueue self.stack2 = [] # For dequeue def enqueue(self, x): self.stack1.append(x) def dequeue(self): if not self.stack2: while self.stack1: self.stack2.append(self.stack1.pop()) if self.stack2: return self.stack2.pop() return None # Queue is empty # Example usage q = QueueUsingStacks() q.enqueue(1) q.enqueue(2) print(q.dequeue()) # Output: 1 print(q.dequeue()) # Output: 2
Advanced Coding Test Practice Questions
21. Find the median of two sorted arrays
def find_median_sorted_arrays(nums1, nums2): nums = sorted(nums1 + nums2) n = len(nums) if n % 2 == 1: return nums[n // 2] else: return (nums[n // 2 - 1] + nums[n // 2]) / 2 # Example usage print(find_median_sorted_arrays([1, 3], [2])) # Output: 2 print(find_median_sorted_arrays([1, 2], [3, 4])) # Output: 2.5
22. Detect a cycle in a linked list
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False # Example usage: # node1 = ListNode(1) # node2 = ListNode(2) # node3 = ListNode(3) # node1.next = node2 # node2.next = node3 # node3.next = node1 # Creates a cycle # print(has_cycle(node1)) # Output: True
23. Implement depth-first search (DFS) and breadth-first search (BFS)
def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start, end=' ') for neighbor in graph.get(start, []): if neighbor not in visited: dfs(graph, neighbor, visited) def bfs(graph, start): visited = set() queue = [start] visited.add(start) while queue: node = queue.pop(0) print(node, end=' ') for neighbor in graph.get(node, []): if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) # Example graph graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } print("DFS: ", end="") dfs(graph, 'A') # Output: DFS: A B D E F C print("\nBFS: ", end="") bfs(graph, 'A') # Output: BFS: A B C D E F
24. Find all subsets of a set
def find_subsets(nums): result = [] def backtrack(start, path): result.append(path) for i in range(start, len(nums)): backtrack(i + 1, path + [nums[i]]) backtrack(0, []) return result # Example usage print(find_subsets([1, 2, 3])) # Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
25. Solve the N-Queens problem
def solve_n_queens(n): def is_safe(row, col): for i in range(row): if board[i] == col or \ board[i] - i == col - row or \ board[i] + i == col + row: return False return True def backtrack(row): if row == n: result.append(board[:]) return for col in range(n): if is_safe(row, col): board[row] = col backtrack(row + 1) result = [] board = [-1] * n backtrack(0) return result # Example usage print(solve_n_queens(4))
26. Implement LRU cache
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.cache = OrderedDict() self.capacity = capacity def get(self, key): if key not in self.cache: return -1 # Move key to end to mark it as recently used self.cache.move_to_end(key) return self.cache[key] def put(self, key, value): if key in self.cache: # Move key to end before updating to mark it as recently used self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: # Pop the least recently used item (first item) self.cache.popitem(last=False) # Example usage lru = LRUCache(2) lru.put(1, 1) lru.put(2, 2) print(lru.get(1)) # Output: 1 lru.put(3, 3) print(lru.get(2)) # Output: -1 (evicted)
27. Find the longest palindromic substring
def longest_palindrome(s): longest = "" for i in range(len(s)): for j in range(i, len(s)): substr = s[i:j+1] if substr == substr[::-1] and len(substr) > len(longest): longest = substr return longest # Example usage print(longest_palindrome("babad")) # Output: "bab" or "aba"
28. Find the maximum sum subarray (Kadane’s Algorithm)
def max_subarray_sum(nums): max_current = max_global = nums[0] for num in nums[1:]: max_current = max(num, max_current + num) if max_current > max_global: max_global = max_current return max_global # Example usage print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])) # Output: 6
29. Implement merge sort
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): result = [] i = j = 0 # Merge two sorted halves while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # Add remaining elements result.extend(left[i:]) result.extend(right[j:]) return result # Example usage print(merge_sort([3, 6, 2, 7, 4, 1])) # Output: [1, 2, 3, 4, 6, 7]
30. Calculate power of a number efficiently
def power(x, n): if n == 0: return 1 half = power(x, n // 2) if n % 2 == 0: return half * half else: return half * half * x # Example usage print(power(2, 10)) # Output: 1024
Bonus Questions
31. Find the intersection point of two linked lists
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def get_intersection_node(headA, headB): if not headA or not headB: return None a, b = headA, headB while a != b: a = a.next if a else headB b = b.next if b else headA return a # Can be the intersection node or None
# Common intersection part intersect = ListNode(8, ListNode(10)) # List A: 3 → 7 → 8 → 10 headA = ListNode(3, ListNode(7, intersect)) # List B: 99 → 1 → 8 → 10 headB = ListNode(99, ListNode(1, intersect)) # Test result = get_intersection_node(headA, headB) print(result.val if result else "No intersection") # Output: 8
32. Implement a function to check balanced parentheses
def is_balanced(s): stack = [] mapping = {')': '(', '}': '{', ']': '['} for char in s: if char in mapping.values(): # opening brackets stack.append(char) elif char in mapping: # closing brackets if not stack or mapping[char] != stack.pop(): return False return not stack # True if stack is empty (balanced) # Example usage print(is_balanced("({[]})")) # Output: True print(is_balanced("({[})")) # Output: False
33. Find the missing ranges in an array
def find_missing_ranges(nums, lower, upper): result = [] prev = lower - 1 nums.append(upper + 1) for num in nums: if num - prev == 2: result.append(str(prev + 1)) elif num - prev > 2: result.append(f"{prev + 1}->{num - 1}") prev = num return result # Example usage print(find_missing_ranges([0, 1, 3, 50, 75], 0, 99)) # Output: ['2', '4->49', '51->74', '76->99']