Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Three Sum (find all triplets summing to zero) is commonly solved by sorting the array and then applying two pointers for each fixed first element. What is the overall time complexity?
- A. O(n^2): O(n log n) to sort plus O(n) two-pointer scan for each of the n choices of the first element
- B. O(n^3), trying every triplet directly
- C. O(n), using a single hash set
- D. O(n log n), same as sorting alone
Correct answer: A. O(n^2): O(n log n) to sort plus O(n) two-pointer scan for each of the n choices of the first element
After an O(n log n) sort, fixing each of the n elements as the smallest of the triplet and two-pointering the rest in O(n) gives O(n) * n = O(n^2) dominating the sort, so O(n^2) overall.
More Coding Interview Problems questions
- Problem: Which statement about Dijkstra's algorithm and negative edge weights is correct?
- Problem: Which best describes the relationship between DFS-based cycle detection in a directed graph and the 'white-gray-black' (or…
- Problem: A bipartite graph check is commonly done by attempting a 2-coloring via BFS/DFS. What does finding an edge between two…
- Problem: What is the time complexity of finding the lowest common ancestor (LCA) of two nodes in a binary tree with n nodes, using a…
- Problem: With O(n) preprocessing (Euler tour + sparse table for range-minimum query), LCA queries on a tree of n nodes can be answered in…
- Problem: Which statement correctly describes the diameter of a tree (the longest path between any two nodes) and how to compute it…