LinkedIn Data Structures and Algorithms Interview Questions & Answers
Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.
About LinkedIn hiring for Data Structures and Algorithms roles
LinkedIn, owned by Microsoft, is a professional networking platform with products for jobs, learning, marketing and sales. Its Bengaluru office hosts a large engineering team building features used globally. It hires in India for software engineers, site reliability engineers, data scientists and analysts working on feeds, search, ads and member engagement metrics.
For Data Structures and Algorithms roles, this LinkedIn practice set focuses most on Linked Lists, Stacks and Queues (7), Sorting, Searching and Backtracking (5), Arrays, Strings and Hashing (5), Graphs and Graph Algorithms (4). It has 1 easy, 20 medium, 9 hard questions, so you can start easy and work up to the harder ones.
Company type
Product
Headquarters
Sunnyvale, California, USA
Main India offices
Bengaluru, Gurugram, Mumbai
LinkedIn Data Structures and Algorithms interview process
Recruiter screening
Technical phone screen
Coding rounds
System design or data science case round
Hiring manager and culture round
Typical pattern based on public candidate experiences. Rounds vary by role, team and year.
Solved for LinkedInStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
Find the lowest common ancestor of two nodes in a binary tree.
def lca(root, p, q):
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left and right: # p and q are on different sides
return root
return left or right
# O(n) time, O(h) space; assumes both nodes exist in the tree
02
How does quicksort work and why does pivot choice matter?
Quicksort picks a pivot, partitions the array so smaller elements go left and larger go right, then recursively sorts both sides. It sorts in place with O(log n) stack space on average and is very cache friendly, averaging O(n log n). A bad pivot, such as always the first element on sorted input, gives unbalanced partitions and O(n squared). Random pivots, median-of-three and three-way partitioning for duplicates avoid this.
03
Implement Dijkstra's algorithm with a priority queue.
Situation: a senior reviewer rejected my pull request because my queue processing code was O(n squared) and had no tests. Task: fix it and learn from it. Action: I asked for a short walkthrough, replaced repeated list removals with a deque, added unit tests for edge cases and asked for a second review. Result: the change merged with a ten times speed-up, and I now self-review complexity and tests before raising any pull request.
05
How do you prioritise when several tasks have deadlines at the same time?
Situation: in one sprint I had a bug fix, a feature and interview preparation for a new hire panel all due together. Task: deliver without dropping quality. Action: I listed the tasks with impact and deadline, discussed the order with my lead, finished the customer-facing bug first, split the feature into smaller deliverables and blocked calendar time for each. Result: everything was delivered within the week and nothing urgent slipped.
06
A hash map lookup in your service suddenly becomes very slow under certain traffic. What could cause it?
If many keys produce the same hash, they pile into a few buckets and operations degrade toward O(n). This can come from a poor custom hashCode, such as returning a constant or using only one field, or from attackers sending crafted keys. Fixes include a better hash function combining all fields, randomised hashing, which Python uses for strings, and tree-based buckets as in Java 8 HashMap, which caps the worst case at O(log n).
07
Implement Union-Find with path compression and union by size.
def rotate(nums, k):
n = len(nums)
k %= n
def reverse(l, r):
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
reverse(0, n - 1) # reverse all
reverse(0, k - 1) # reverse first k
reverse(k, n - 1) # reverse the rest
# [1,2,3,4,5,6,7], k=3 -> [5,6,7,1,2,3,4]; O(n) time, O(1) space
09
Find the shortest path length from the top-left to the bottom-right of a grid where 1 is a wall.
from collections import deque
def shortest_path(grid):
R, C = len(grid), len(grid[0])
if grid[0][0] or grid[R-1][C-1]:
return -1
q = deque([(0, 0, 1)])
seen = {(0, 0)}
while q:
r, c, d = q.popleft()
if (r, c) == (R - 1, C - 1):
return d
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and not grid[nr][nc] and (nr, nc) not in seen:
seen.add((nr, nc))
q.append((nr, nc, d + 1))
return -1
# BFS: O(R * C)
10
What is a monotonic stack and which problems does it solve?
A monotonic stack keeps its elements in increasing or decreasing order by popping elements that break the order before each push. Each element is pushed and popped at most once, so a full pass is O(n). It solves next greater or next smaller element, daily temperatures, stock span, largest rectangle in a histogram and trapping rain water, replacing O(n squared) nested scans with a single linear scan.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps the sort stable
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
# O(n log n) time, O(n) extra space
12
Your knapsack DP has n equal to 100 items but capacity up to 10 to the power 9, so the table does not fit in memory. What do you do?
A table indexed by capacity is impossible, so I change the state. If item values are small, use dp[v] as the minimum weight needed to achieve value v, then pick the largest v whose weight fits the capacity; that is O(n times total value). If n is about 40, meet in the middle: enumerate subsets of each half, sort one side and binary search. Otherwise approximation or branch and bound are options.
13
Return an array where each element is the product of all other elements, without using division.
def product_except_self(nums):
n = len(nums)
out = [1] * n
prefix = 1
for i in range(n): # product of everything to the left
out[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1): # multiply by everything to the right
out[i] *= suffix
suffix *= nums[i]
return out
# [1,2,3,4] -> [24,12,8,6]; O(n) time, O(1) extra space besides output
14
Design a rate limiter that allows at most 100 requests per user in any rolling 60-second window.
For each user keep a deque of request timestamps. On a request, pop timestamps older than now minus 60 seconds from the front, then allow the request only if fewer than 100 remain, pushing the new timestamp at the back. This sliding window log is exact but uses memory per request. At scale I would use a sliding window counter or token bucket stored in Redis with atomic operations to save memory and work across servers.
15
Generate all permutations of a list of distinct numbers using backtracking.
def permutations(nums):
result, path = [], []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i, x in enumerate(nums):
if used[i]:
continue
used[i] = True
path.append(x)
backtrack()
path.pop() # undo the choice
used[i] = False
backtrack()
return result
# n! permutations: O(n * n!) time
16
A report generation function loops over all users and, for each user, scans all orders. It was fine at launch but is now very slow. How do you explain and fix it?
The loop is O(users times orders), so when both grow ten times, the work grows a hundred times. I would explain this with numbers and a quick profile. The fix is to group orders by user ID once using a hash map, making the total O(users plus orders), or to push the grouping into a database query with an index. I would add a performance test with production-scale data.
17
A sorted array has been rotated at an unknown point. How can you still search it in O(log n)?
At every step of binary search, at least one half around mid is sorted. Compare nums[low] with nums[mid]: if the left half is sorted and the target lies within its range, search left, otherwise search right. If the right half is sorted, apply the same check on the right. This keeps O(log n). With duplicates allowed, equal values can hide which half is sorted, and the worst case becomes O(n).
18
Find the first and last position of a target in a sorted array.
from bisect import bisect_left, bisect_right
def search_range(nums, target):
lo = bisect_left(nums, target) # first index >= target
if lo == len(nums) or nums[lo] != target:
return [-1, -1]
hi = bisect_right(nums, target) - 1 # last index <= target
return [lo, hi]
# [5,7,7,8,8,10], 8 -> [3, 4]; two binary searches: O(log n)
19
How do you handle pressure during a timed online coding test?
Situation: in a 90-minute test I faced three problems, one of them a tough DP. Task: maximise my score. Action: I read all problems first, solved the easiest one quickly to secure marks, wrote a brute-force version of the DP problem for partial credit, then improved it to memoised DP once I spotted the state. I kept an eye on time at fixed checkpoints. Result: I cleared all test cases on two problems and most of the third.
20
A search box must suggest the closest dictionary words when a user makes a typo. How would you approach it?
Compute edit distance between the typed word and candidate words, suggesting those within distance 1 or 2. Running O(m times n) DP against a whole dictionary is slow, so narrow candidates first using a BK-tree indexed by edit distance, a trie with bounded edit distance search, or n-gram indexes. Then rank candidates by distance and word popularity. Keyboard-aware substitution costs can improve suggestions further.
21
How does Floyd's cycle detection algorithm work and why is it correct?
Floyd uses a slow pointer moving one step and a fast pointer moving two steps. If there is no cycle, fast reaches the end. If there is a cycle, fast gains one step per iteration on slow inside the loop, so they must meet. To find the cycle start, reset one pointer to the head and move both one step at a time; they meet at the start because the distances from head and from the meeting point are equal modulo the cycle length.
22
How did you prepare for data structures and algorithms rounds?
Situation: I was weak at DSA in my third year. Task: become placement-ready in five months. Action: I followed a topic-wise plan, solved around 300 problems by pattern such as sliding window, BFS and DP, kept a notebook of mistakes, revised weekly and took timed contests every weekend. I also practised explaining solutions aloud. Result: my speed improved steadily and I cleared coding rounds at two product companies.
23
Count the number of islands in a grid of 1s and 0s.
// Java
static int numIslands(char[][] g) {
int count = 0;
for (int r = 0; r < g.length; r++)
for (int c = 0; c < g[0].length; c++)
if (g[r][c] == '1') { count++; sink(g, r, c); }
return count;
}
static void sink(char[][] g, int r, int c) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
g[r][c] = '0'; // mark visited
sink(g, r + 1, c); sink(g, r - 1, c);
sink(g, r, c + 1); sink(g, r, c - 1);
}
// O(rows * cols) time
24
A recursive DFS in Python crashes with RecursionError on a deep input. How do you fix it?
CPython limits recursion depth to about 1000 by default. Raising the limit with sys.setrecursionlimit works for moderate depth but can crash the interpreter on very deep inputs because the C stack is limited. The reliable fix is to rewrite the DFS iteratively with an explicit stack, pushing nodes and processing them in a loop. In Java the same issue appears as StackOverflowError and has the same solution.
25
You must merge two sorted arrays where the first array has enough empty space at the end for the second. How would you do it in place?
Merging from the front would overwrite unread elements, so merge from the back. Use three pointers: the last real element of the first array, the last element of the second, and the last slot of the first array. Repeatedly place the larger of the two candidates at the write position and move pointers left. When the second array is exhausted, the rest is already in place. This takes O(m plus n) time and O(1) space.
def reverse_k_group(head, k):
# check that k nodes are available
node, count = head, 0
while node and count < k:
node = node.next
count += 1
if count < k:
return head # leave the remainder as is
prev, cur = None, head
for _ in range(k): # reverse k nodes
cur.next, prev, cur = prev, cur, cur.next
head.next = reverse_k_group(cur, k) # old head is now the group tail
return prev
# 1-2-3-4-5, k=2 -> 2-1-4-3-5; O(n) time
27
How does a monotonic deque find the maximum of every sliding window in O(n)?
Keep a deque of indices whose values are in decreasing order. For each new element, pop from the back while the back value is smaller, since those elements can never be the maximum again, then push the new index. Pop from the front if its index has left the window. The front is always the maximum of the current window. Every index enters and leaves once, so the total time is O(n) instead of O(n times k).
28
A trading application needs a stack that also returns the current minimum in O(1). How would you design it?
Keep a second stack of minimums. On push, push the value onto the main stack and push the smaller of the value and the current minimum onto the min stack. On pop, pop both. getMin returns the top of the min stack in O(1). To save space, push onto the min stack only when the new value is less than or equal to the current minimum, and pop it only when the popped value equals it.
29
How does a hash table work, and how are collisions handled?
A hash table computes a hash of the key and maps it to a bucket index, giving average O(1) insert, lookup and delete. A collision happens when two keys map to the same bucket. Separate chaining stores a list or tree in each bucket, which Java HashMap uses and converts to a tree after 8 entries. Open addressing probes other slots, which Python dict uses. Tables resize when the load factor grows too high.
import heapq
def merge_k_lists(lists):
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node)) # i breaks ties
dummy = tail = ListNode()
while heap:
val, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
# O(N log K) for N total nodes
Tips to crack the LinkedIn Data Structures and Algorithms interview
Practise metric definition questions about LinkedIn features like job recommendations, feed engagement or InMail response rates.
Prepare DSA on graphs, since social network problems such as degrees of connection are a natural interview theme.
Read LinkedIn's culture and values, including Members First, and connect them to your past teamwork examples.
Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
Practise the hard questions on this page aloud; LinkedIn interviewers usually ask follow-ups on your first answer.
Frequently asked questions
How many rounds are there in the LinkedIn Data Structures and Algorithms interview?
Candidates usually go through 5 stages: Recruiter screening; Technical phone screen; Coding rounds; System design or data science case round; Hiring manager and culture round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.
Which topics should I prepare for the LinkedIn Data Structures and Algorithms interview?
This practice set leans on Linked Lists, Stacks and Queues (7), Sorting, Searching and Backtracking (5), Arrays, Strings and Hashing (5), Graphs and Graph Algorithms (4). Revise those first, then practise explaining one or two of your own projects end to end, because most LinkedIn interviewers ask you to walk through real work.
Are these the exact questions asked at LinkedIn?
No. These are curated practice questions that match the skills and difficulty usually tested in product interviews like LinkedIn's. They are not a leaked or verified list of past questions.
Where does LinkedIn hire Data Structures and Algorithms professionals in India?
LinkedIn has large teams in Bengaluru, Gurugram, Mumbai. Openings and locations change often, so check the LinkedIn careers page and filter by city and experience.
Data Structures and Algorithms questions for similar companies