Interview questions · Meta
Implement list cloning and k-frequency finder
The first part evaluates understanding of linked data structures and deep-copy semantics, focusing on preserving node values and both next and arbitrary random pointer relationships while reasoning about node identity and cycles, and is commonly asked to assess correctness in memory/reference handling and structural preservation.
You are given two separate coding tasks.
Problem 1: Deep copy a linked list with extra pointers
You are given the head of a singly linked list. Each node has three fields:
val: an integer valuenext: a pointer (or reference) to the next node in the list, ornullif it is the last noderandom: a pointer (or reference) to any node in the list (including possibly itself) ornull
The list may contain zero or more nodes.
Task: Implement a function that creates a deep copy of this list. The new list must:
- Contain the same number of nodes as the original.
- Preserve the
valvalues. - Preserve the structure of both the
nextandrandompointers: for every original node, its copy'snextandrandomshould point to the copies of the corresponding original targets. - Share no nodes with the original list (i.e., all nodes in the copied list must be newly allocated).
Return the head of the copied list.
You may assume:
- Number of nodes satisfies .
- The input list may contain arbitrary
randompointer configurations, including cycles formed viarandompointers.
You should aim for time complexity and additional space.
Problem 2: Find the k most frequent integers in an array
You are given an integer array nums and an integer k where .
Task:
Return any order of the k distinct integers that appear most frequently in nums.
- If multiple numbers have the same frequency and they are in the top
kby frequency, any order among them is acceptable. - The output should contain exactly
kdistinct integers.
Examples
Example 1:
- Input:
nums = [1, 1, 1, 2, 2, 3],k = 2 - One valid output:
[1, 2](because1appears 3 times,2appears 2 times,3appears 1 time)
Example 2:
- Input:
nums = [4, 4, 4, 5, 5, 6],k = 1 - One valid output:
[4](since it is the most frequent element)
You may assume:
- The number of distinct values in
numsis at leastk.
Aim for an algorithm that runs in better than time, where is the length of nums.
Community answers
Nothing here yet.
Join in on CSWork →