Top 50 DSA Interview Questions & Answers Asked at Top Tech Companies
Prepare for technical interviews with 50 DSA questions and answers asked at top tech companies. Covers arrays, strings, linked lists, trees, graphs, dynamic programming, and more.
SV
Shubhankar Vashist
01 Jan 1970
157 min read
Top 50 DSA Interview Questions & Answers Asked at Top Tech Companies (2026)
The interviewer leans forward and asks, "Given an array of integers, find the contiguous subarray with the largest sum."
You recognize the problem. Kadane's Algorithm. You have seen it before. But can you explain it clearly? Can you handle the follow-up questions? Can you code it correctly under pressure? Can you discuss the time and space complexity?
Technical interviews at top technology companies test exactly this. Not just whether you know algorithms, but whether you can apply them under pressure, explain your thinking clearly, and handle variations of familiar problems.
This guide covers 50 DSA interview questions commonly asked at top tech companies in 2026. The questions span arrays, strings, linked lists, trees, graphs, dynamic programming, and other core topics. Each question includes the approach, key insight, and complexity analysis
Array Interview Questions
Two Sum
Problem: Given an array of integers and a target sum, find two numbers that add up to the target.
Approach: Use a hash map to store numbers you have seen and their indices. For each number, check if its complement (target minus current number) exists in the map. If it does, return both indices. If not, add the current number to the map.
Time Complexity: O(n) because you traverse the array once.
Space Complexity: O(n) for the hash map
Key Insight: The hash map provides O(1) lookup, converting what would be a nested loop O(n²) into linear time.
Best Time to Buy and Sell Stock
Problem: Given an array of stock prices, find the maximum profit from buying and selling once
Approach: Track the minimum price seen so far and the maximum profit possible. For each price, update the minimum if the current price is lower. Calculate potential profit if selling at the current price. Update maximum profit if the potential profit exceeds the current maximum.
Time Complexity: O(n) single pass through the array
Space Complexity: O(1) constant extra space.
Key Insight: The maximum profit at any point is the current price minus the minimum price seen before that point
Maximum Subarray (Kadane's Algorithm)
Problem: Find the contiguous subarray with the largest sum.
Approach: Track the maximum sum ending at the current position and the overall maximum sum. For each element, decide whether to start a new subarray at this element or continue the existing subarray. The choice depends on which gives a larger sum
Time Complexity: O(n) single pass
Space Complexity: O(1) constant space.
Key Insight: At each position, the maximum subarray ending there is either the element alone or the element plus the maximum subarray ending at the previous position. Choose the larger.
Product of Array Except Self
Problem: Return an array where each element is the product of all other elements except itself. Do not use division
Approach: Use two passes. The first pass calculates the product of all elements to the left of each position. The second pass calculates the product of all elements to the right. Multiply left and right products for each position.
Time Complexity: O(n) two passes
Space Complexity: O(1) excluding the output array.
Key Insight: Each element's result is the product of everything to its left multiplied by everything to its right. Two passes capture both.
Contains Duplicate
Problem: Determine if an array contains any duplicate elements
Approach: Use a hash set. Traverse the array, adding each element to the set. If an element already exists in the set, return true. If the traversal completes without finding duplicates, return false
Time Complexity: O(n) single pass.
Space Complexity: O(n) for the hash set
Key Insight: The hash set provides O(1) membership checking, making duplicate detection linear time.
Find Minimum in Rotated Sorted Array
Problem: A sorted array has been rotated. Find the minimum element.
Approach: Use modified binary search. Compare the middle element with the rightmost element. If the middle is greater than the rightmost, the minimum is in the right half. If the middle is less than or equal to the rightmost, the minimum is in the left half including the middle.
Time Complexity: O(log n) binary search
Space Complexity: O(1) constant space.
Key Insight: The comparison with the rightmost element determines which half contains the rotation point and therefore the minimum
Search in Rotated Sorted Array
Problem: Search for a target value in a rotated sorted array.
Approach: Use modified binary search. Determine which half of the array is normally ordered. Check if the target falls within the ordered half. If it does, search that half. If not, search the other half.
Time Complexity: O(log n) binary search
Space Complexity: O(1) constant space.
Key Insight: In a rotated sorted array, at least one half is always properly sorted. Determining which half and checking the target against it enables binary search.
Three Sum
Problem: Find all unique triplets that sum to zero
Approach: Sort the array first. For each element, use two pointers to find pairs in the remaining array that sum to the negative of the current element. Skip duplicates to avoid repeated triplets
Time Complexity: O(n²) because for each element, the two-pointer scan is O(n).
Space Complexity: O(1) excluding output storage.
Key Insight: Sorting enables the two-pointer technique and duplicate skipping. The problem reduces from O(n³) to O(n²)
Container With Most Water
Problem: Given heights of vertical lines, find the maximum water container area
Approach: Use two pointers at the ends of the array. Calculate the area between the pointers. Move the pointer with the smaller height toward the center. Continue until pointers meet
Time Complexity: O(n) single pass.
Space Complexity: O(1) constant space.
Key Insight: The area is limited by the shorter line. Moving the shorter pointer inward might find a taller line that increases area. Moving the taller pointer cannot increase area.
Merge Intervals
Problem: Merge overlapping intervals
Approach: Sort intervals by start time. Traverse the sorted intervals. If the current interval overlaps with the previous merged interval, merge them. If not, add the previous merged interval to the result and start a new one.
Time Complexity: O(n log n) for sorting.
Space Complexity: O(n) for the output.
Key Insight: Sorting by start time ensures that overlapping intervals are adjacent. The merge process is then linear
String Interview Questions
Valid Anagram
Problem: Determine if two strings are anagrams.
Approach: Count character frequencies in both strings. If the frequency maps match, the strings are anagrams. Alternatively, sort both strings and compare
Time Complexity: O(n) for frequency counting. O(n log n) for sorting approach
Space Complexity: O(1) for frequency counting since character set is limited
Key Insight: Anagrams have identical character frequency distributions. Counting frequencies captures this.
Valid Parentheses
Problem: Determine if a string of brackets is valid
Approach: Use a stack. Push opening brackets onto the stack. For closing brackets, check if the stack top has the matching opening bracket. If it does, pop. If not, the string is invalid. At the end, the stack should be empty.
Time Complexity: O(n) single pass.
Space Complexity: O(n) for the stack
Key Insight: The stack naturally matches the most recent opening bracket with the current closing bracket, reflecting the nesting structure of valid parentheses.
Longest Substring Without Repeating Characters
Problem: Find the length of the longest substring without repeating characters.
Approach: Use the sliding window technique. Maintain a window with no repeating characters. Track character positions in a hash map. When a duplicate is found, move the window start to after the previous occurrence
Time Complexity: O(n) single pass
Space Complexity: O(min(n, m)) where m is the character set size
Key Insight: The sliding window expands until a duplicate appears, then contracts by moving the start. The hash map tracks character positions for efficient window adjustment
Longest Palindromic Substring
Problem: Find the longest palindromic substring.
Approach: Use the expand around center technique. For each character and each pair of adjacent characters as a center, expand outward while characters match. Track the longest palindrome found.
Time Complexity: O(n²) because there are O(n) centers and each expansion is O(n).
Space Complexity: O(1) constant space.
Key Insight: A palindrome is symmetric around its center. Checking all possible centers captures all palindromes, both odd and even length
Group Anagrams
Problem: Group strings that are anagrams of each other
Approach: For each string, create a sorted version of the string as a key. Strings with the same sorted version are anagrams. Use a hash map to group strings by their sorted key
Time Complexity: O(n × k log k) where n is the number of strings and k is the average string length
Space Complexity: O(n × k) for the output.
Key Insight: Sorted strings serve as canonical keys for anagram groups. Anagrams always produce the same sorted string.
String to Integer (atoi)
Problem: Convert a string to an integer with proper handling of whitespace, signs, and overflow
Approach: Trim whitespace. Handle optional sign. Parse digits while checking for overflow. Handle edge cases like empty string and non-digit characters.
Time Complexity: O(n) single pass
Space Complexity: O(1) constant space.
Key Insight: The problem tests careful handling of edge cases rather than complex algorithms. Overflow checking requires comparing against limits before multiplying
Longest Common Prefix
Problem: Find the longest common prefix among an array of strings.
Approach: Compare characters position by position across all strings. Continue while all strings have the same character at the current position. Stop when a mismatch is found.
Time Complexity: O(S) where S is the sum of all characters
Space Complexity: O(1) excluding output.
Key Insight: The common prefix cannot be longer than the shortest string. Checking characters position by position finds the prefix efficiently.
Count and Say
Problem: Generate the nth term of the count-and-say sequence.
Approach: Start with "1". For each subsequent term, read the current term and describe it. Count consecutive identical digits and say the count followed by the digit.
Time Complexity: O(n × k) where k is the average term length
Space Complexity: O(k) for the current term.
Key Insight: The sequence is generated by describing the previous term. The description process is straightforward counting of consecutive identical characters.
Linked List Interview Questions
Reverse Linked List
Problem: Reverse a singly linked list
Approach: Use three pointers: previous, current, and next. For each node, save the next node, point the current node to the previous node, then move previous and current forward.
Time Complexity: O(n) single pass
Space Complexity: O(1) constant space for iterative approach.
Key Insight: Reversing pointers one by one transforms the list. The iterative approach uses constant space and is preferred over recursion
Detect Cycle in Linked List
Problem: Determine if a linked list contains a cycle.
Approach: Use Floyd's cycle detection algorithm with two pointers. The slow pointer moves one step at a time. The fast pointer moves two steps. If they meet, a cycle exists. If the fast pointer reaches null, no cycle exists
Time Complexity: O(n) for traversal.
Space Complexity: O(1) constant space
Key Insight: Two pointers moving at different speeds will eventually meet if a cycle exists. The technique uses constant space unlike hash map approaches
Merge Two Sorted Lists
Problem: Merge two sorted linked lists into one sorted list.
Approach: Compare the head nodes of both lists. Add the smaller to the result. Move the corresponding list forward. Continue until one list is exhausted, then append the remaining list
Time Complexity: O(n + m) where n and m are list lengths.
Space Complexity: O(1) for iterative approach using existing nodes.
Key Insight: The merge process mirrors the merge step of merge sort. Comparing heads and moving pointers preserves order.
Remove Nth Node From End of List
Problem: Remove the nth node from the end of a linked lis
Approach: Use two pointers. Move the first pointer n steps ahead. Then move both pointers together until the first reaches the end. The second pointer now points to the node before the target. Remove the target.
Time Complexity: O(n) single pass.
Space Complexity: O(1) constant space
Key Insight: The two-pointer technique with a gap of n positions enables finding the nth node from the end in one pass without knowing the list length
Find Middle of Linked List
Problem: Find the middle node of a linked list.
Approach: Use two pointers. The slow pointer moves one step. The fast pointer moves two steps. When the fast pointer reaches the end, the slow pointer is at the middle.
Time Complexity: O(n) single pass.
Space Complexity: O(1) constant space
Key Insight: The fast pointer moves twice as fast, so when it reaches the end, the slow pointer has covered half the distance
Palindrome Linked List
Problem: Determine if a linked list is a palindrome.
Approach: Find the middle using slow and fast pointers. Reverse the second half. Compare the first half with the reversed second half. Restore the list if needed
Time Complexity: O(n) multiple passes
Space Complexity: O(1) constant space.
Key Insight: Reversing the second half allows comparison with the first half in constant extra space. The technique avoids storing the entire list.
Intersection of Two Linked Lists
Problem: Find the intersection node of two linked lists.
Approach: Calculate the lengths of both lists. Align the starts by moving the longer list's pointer forward by the length difference. Then move both pointers together until they mee
Time Complexity: O(n + m) for length calculation and traversal
Space Complexity: O(1) constant space.
Key Insight: Aligning the starts by length difference ensures that when the pointers meet, they are at the intersection or both at nul
Tree Interview Questions
Maximum Depth of Binary Tree
Problem: Find the maximum depth of a binary tree.
Approach: Use recursion. The depth of a node is 1 plus the maximum depth of its children. The base case is a null node with depth 0
Time Complexity: O(n) visits every node.
Space Complexity: O(h) for recursion stack where h is tree height.
Key Insight: The recursive definition mirrors the tree structure naturally. Each node's depth is determined by its deepest child
Invert Binary Tree
Problem: Invert a binary tree by swapping left and right children.
Approach: Use recursion. For each node, swap its left and right children. Then recursively invert the left and right subtrees
Time Complexity: O(n) visits every node.
Space Complexity: O(h) for recursion stack
Key Insight: The inversion is a simple swap at each node followed by recursive inversion of subtrees. The recursion handles the entire tree.
Validate Binary Search Tree
Problem: Determine if a binary tree is a valid binary search tree.
Approach: Use recursion with min and max bounds. Each node's value must be within its allowed range. The left child must be less than the parent. The right child must be greater than the parent. Update bounds recursively.
Time Complexity: O(n) visits every node.
Space Complexity: O(h) for recursion stack.
Key Insight: The bounds approach ensures that all nodes in the left subtree are less than the parent, not just the immediate child. This is the common mistake the problem tests.
Level Order Traversal
Problem: Traverse a binary tree level by level.
Approach: Use a queue. Start with the root. For each level, process all nodes currently in the queue, add their values to the result, and enqueue their children.
Time Complexity: O(n) visits every node.
Space Complexity: O(w) where w is the maximum width.
Key Insight: The queue naturally processes nodes level by level because it preserves the order of insertion and processes all nodes at one level before moving to the next
Construct Binary Tree from Preorder and Inorder Traversal
Problem: Build a binary tree from preorder and inorder traversals.
Approach: The first element of preorder is the root. Find the root in inorder. Elements before the root in inorder form the left subtree. Elements after form the right subtree. Recursively build subtrees.
Time Complexity: O(n) with hash map for inorder lookup.
Space Complexity: O(n) for hash map and recursion stack.
Key Insight: Preorder gives the root order. Inorder gives the subtree structure. Combining them enables tree reconstruction
Lowest Common Ancestor of BST
Problem: Find the lowest common ancestor of two nodes in a binary search tree.
Approach: Use the BST property. If both nodes are less than the current node, search left. If both are greater, search right. If one is less and one is greater, the current node is the LCA.
Time Complexity: O(h) where h is tree height.
Space Complexity: O(1) for iterative approach.
Key Insight: The BST property makes LCA finding simple. The first node where the two targets diverge is the LCA.
Diameter of Binary Tree
Problem: Find the longest path between any two nodes in a binary tree.
Approach: Use recursion to calculate height while tracking the diameter. The diameter at each node is the sum of left height and right height. The maximum diameter across all nodes is the answer.
Time Complexity: O(n) visits every node
Space Complexity: O(h) for recursion stack
Key Insight: The longest path passes through some node and equals the height of its left subtree plus the height of its right subtree. Tracking this at every node finds the maximum.
Graph Interview Questions
Number of Islands
Problem: Count the number of islands in a grid of water and land.
Approach: Use DFS or BFS. Traverse the grid. When land is found, increment the island count and mark all connected land as visited by flooding the island.
Time Complexity: O(n × m) visits every cell.
Space Complexity: O(n × m) worst case for recursion stack or queue.
Key Insight: Each island is a connected component. Flooding each discovered island prevents double counting.
Clone Graph
Problem: Deep clone a graph
Approach: Use DFS or BFS with a hash map. The map tracks original nodes and their clones. For each node, clone it and recursively clone its neighbors.
Time Complexity: O(n + e) visits every node and edge.
Space Complexity: O(n) for the hash map
Key Insight: The hash map prevents infinite loops from cycles in the graph and ensures that each original node maps to exactly one clone.
Course Schedule
Problem: Determine if all courses can be completed given prerequisites.
Approach: Model as a directed graph. Use topological sorting or cycle detection. If the graph contains a cycle, courses cannot be completed. If no cycle, completion is possible.
Time Complexity: O(n + e) for graph traversal.
Space Complexity: O(n + e) for graph representation
Key Insight: Prerequisites create dependencies. A cycle in the dependency graph makes completion impossible. Topological sort detects cycles
Word Ladder
Problem: Find the shortest transformation sequence from one word to another, changing one letter at a time
Approach: Use BFS. Each word is a node. Words differing by one letter are connected. BFS finds the shortest path from start to end.
Time Complexity: O(n × k) where n is word count and k is word length.
Space Complexity: O(n) for the queue and visited set.
Key Insight: BFS guarantees the shortest path in an unweighted graph. The transformation sequence is a shortest path problem
Pacific Atlantic Water Flow
Problem: Find cells from which water can flow to both Pacific and Atlantic oceans
Approach: Use DFS or BFS from both oceans. Mark cells reachable from each ocean. Cells reachable from both are the answer.
Time Complexity: O(n × m) visits every cell.
Space Complexity: O(n × m) for visited tracking.
Key Insight: Instead of checking each cell, work backward from the oceans. Cells reachable from both oceans satisfy the condition.
Rotting Oranges
Problem: Determine how long it takes for all oranges to rot.
Approach: Use multi-source BFS. Start from all initially rotten oranges. Each minute, rot spreads to adjacent fresh oranges. Track time and remaining fresh oranges
Time Complexity: O(n × m) visits every cell.
Space Complexity: O(n × m) for the queue.
Key Insight: Multi-source BFS processes rot propagation level by level, where each level represents one minute of spread.b
Dynamic Programming Interview Questions
Climbing Stairs
Problem: Count ways to climb n stairs taking 1 or 2 steps at a time.
Approach: Use dynamic programming. The ways to reach step n equals ways to reach step n-1 plus ways to reach step n-2. This is the Fibonacci sequence.
Time Complexity: O(n) single pass
Space Complexity: O(1) tracking only two previous values.
Key Insight: The recurrence relation is simple: f(n) = f(n-1) + f(n-2). The problem is a disguised Fibonacci sequence.
Coin Change
Problem: Find the minimum number of coins to make a given amount
Approach: Use dynamic programming. Create an array where dp[i] is the minimum coins for amount i. For each amount, try each coin and take the minimum.
Time Complexity: O(amount × coins).
Space Complexity: O(amount) for the DP array
Key Insight: The optimal solution for amount i builds on optimal solutions for smaller amounts. The recurrence is dp[i] = min(dp[i - coin] + 1).
Longest Increasing Subsequence
Problem: Find the length of the longest increasing subsequence
Approach: Use dynamic programming with binary search. Maintain an array representing the smallest possible tail for subsequences of each length. Update with binary search
Time Complexity: O(n log n) with binary search optimization
Space Complexity: O(n) for the DP array.
Key Insight: The tails array captures the minimum possible last element for increasing subsequences of each length. Binary search finds insertion positions.
Longest Common Subsequence
Problem: Find the length of the longest common subsequence of two strings.
Approach: Use dynamic programming. Create a 2D table where dp[i][j] is the LCS length for prefixes. If characters match, add 1 to the diagonal. If not, take the maximum of left and up.
Time Complexity: O(n × m) for the DP table
Space Complexity: O(n × m) for the DP table
Key Insight: The recurrence captures the choice of including or excluding characters. Matching characters extend the LCS. Non-matching characters propagate the best previous result.
Edit Distance
Problem: Find the minimum operations to convert one string to another using insert, delete, and replace.
Approach: Use dynamic programming. Create a 2D table. Each cell represents the minimum operations for prefixes. The recurrence considers insert, delete, and replace operations.
Time Complexity: O(n × m) for the DP table
Space Complexity: O(n × m) for the DP table.
Key Insight: The three operations correspond to three directions in the DP table. The minimum of the three plus one gives the current cell value, except when characters match.
House Robber
Problem: Maximize stolen money from houses without robbing adjacent houses.
Approach: Use dynamic programming. For each house, the maximum is either skip this house and take the previous maximum, or rob this house and take the maximum from two houses back.
Time Complexity: O(n) single pass
Space Complexity: O(1) tracking two values
Key Insight: The recurrence is dp[i] = max(dp[i-1], dp[i-2] + nums[i]). The choice is between skipping and robbing the current house
Decode Ways
Problem: Count ways to decode a string of digits into letters
Approach: Use dynamic programming. Each digit can decode alone if between 1 and 9. Two digits can decode together if between 10 and 26. The total ways is the sum of both possibilities
Time Complexity: O(n) single pass.
Space Complexity: O(n) for the DP array
Key Insight: The recurrence is dp[i] = dp[i-1] for single digit decode plus dp[i-2] for two-digit decode, with validity checks for each.
Additional Frequently Asked Questions
Implement a Queue using Stacks
Approach: Use two stacks. Push elements onto the first stack. For pop and peek, if the second stack is empty, transfer all elements from the first stack to the second stack. The top of the second stack is the front of the queue
Time Complexity: O(1) amortized for push and pop.
Space Complexity: O(n) for both stacks
Key Insight: Transferring elements between stacks reverses their order, converting stack LIFO behavior into queue FIFO behavior.
Implement a Stack using Queues
Approach: Use two queues. For push, add to the first queue. For pop, transfer all elements except the last from the first queue to the second, pop the last element, then swap queues.
Time Complexity: O(n) for push or pop depending on implementation.
Space Complexity: O(n) for both queues
Key Insight: Rotating elements between queues simulates stack behavior. The last element added becomes accessible first.
LRU Cache
Problem: Design a cache with get and put operations in O(1) time, evicting least recently used items.
Approach: Use a hash map and a doubly linked list. The map provides O(1) lookup. The linked list maintains usage order. Most recently used items at the front. Least recently used at the back.
Time Complexity: O(1) for both get and put.
Space Complexity: O(capacity) for stored items.
Key Insight: The combination of hash map for lookup and linked list for ordering provides O(1) operations. The linked list enables efficient reordering
Median of Two Sorted Arrays
Problem: Find the median of two sorted arrays
Approach: Use binary search on the smaller array. Partition both arrays such that elements on the left are smaller than elements on the right. The median is derived from the partition
Time Complexity: O(log(min(n, m))) binary search
Space Complexity: O(1) constant space
Key Insight: The partition approach finds the correct split point without merging. Binary search on the smaller array finds the split in logarithmic time.
Trapping Rain Water
Problem: Calculate trapped rainwater given an elevation array
Approach: Use two pointers. Track maximum heights from left and right. Water trapped at each position is the minimum of left and right maxima minus the current height
Time Complexity: O(n) single pass.
Space Complexity: O(1) constant space.
Key Insight: Water at each position is bounded by the shorter of the maximum heights on either side. Two pointers track these maxima efficiently.
How to Prepare Using These Questions
Reading questions and answers is a starting point. Effective preparation requires active practice
Solve each problem yourself before reading the solution. The struggle of attempting the problem develops problem-solving skills that reading solutions cannot.
Explain your approach aloud as you solve. The verbal explanation prepares you for interview communication
Handle variations and follow-ups. What if the input is sorted? What if you need to return all solutions? What if there are memory constraints? The follow-ups test deeper understanding.
Practice under time constraints. Interviews are timed. The pressure affects performance. Practice with time limits to simulate interview conditions.
Review regularly. The goal is pattern recognition, not memorization. Regular review consolidates patterns.
Conclusion
The 50 questions covered in this guide span the core DSA topics that top tech companies test. Arrays, strings, linked lists, trees, graphs, dynamic programming, and design problems. Each question tests specific patterns and techniques.
The key to success is not memorizing solutions. It is understanding patterns. Two pointers. Sliding window. Binary search. BFS vs DFS. Dynamic programming recurrence. Once you recognize the pattern, you can solve any variation
Preparation requires consistent practice. Solve problems daily. Review regularly. Explain your thinking aloud. The effort invested in preparation pays off in interview performance and career opportunities.
If you are preparing for technical interviews, SkillsYard's Engineering Program covers data structures, algorithms, and problem-solving through structured learning with mentorship. The program prepares you for interviews at top tech companies.
The combination of structured learning and consistent practice creates the fastest path to interview success. If you are still exploring whether this path fits your goals, a free demo session is an easy way to see if practical engineering training aligns with your career direction
Related Courses
Digital Marketing
INTERMEDIATE
Advance Certification in Digital Marketing
A comprehensive year-long program covering the entire spectrum of Digital Marketing—from foundational concepts like SEO and SMM to advanced strategies in paid advertising, analytics, content marketing, and production-ready campaigns.
digital marketingseosocial media marketingemail marketinggoogle analyticsaffiliate marketing
6 months
BEGINNER
Advance Certification in SEO Specialist
A specialized program focused on mastering SEO at an expert level—from core principles like keyword research and on-page optimization to advanced skills in technical SEO, link-building, analytics, and driving sustainable organic growth.
An intensive program designed to master the art of E-Commerce Marketing—covering everything from store optimization and conversion strategies to advanced techniques in performance marketing, customer retention, automation, and building scalable online businesses.