Solve Quickselect, Tree Distance, and Prefix Substrings
GoogleSoftware Engineer · OnsiteLast updated
This multi-part question evaluates algorithmic problem-solving across selection algorithms, graph/tree traversal, and string processing, testing competencies such as Quickselect behavior and pivot reasoning, computation of node distances in a tree, and prefix-based substring counting.
You are given three independent coding tasks.
- Implement Quickselect
- Given an unsorted integer array
numsand an integerk, return thek-th smallest element, wherekis 1-indexed. - Duplicates may appear in the array.
- Discuss different approaches, their time complexities, and how you would choose a pivot for Quickselect.
- Implement one valid approach.
- Find the distance between two nodes in a tree
- You are given an undirected tree as a list of edges and two target nodes
uandv. - Return the number of edges on the unique path between
uandv. - If
u == v, return0. - If either node does not exist, return
-1. - You may assume the input edges form a valid tree unless otherwise specified. Be prepared to discuss how you would validate duplicate edges or invalid tree input.
- Count substrings with a given prefix
- Given a string
sand a non-empty stringtarget, count how many substrings ofshavetargetas their prefix. - A substring
s[i:j]is valid if its firstlen(target)characters exactly equaltarget. - Return the count as a 64-bit integer.
- Follow-up: return the length of the shortest valid substring. If no valid substring exists, return
-1.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.