Solve a two-jug measuring problem
SnapchatSoftware Engineer · Technical ScreenLast updated
This question evaluates algorithm design, state-space modeling, graph-search techniques (BFS/DFS) and number-theoretic reasoning (gcd), along with handling edge cases and analyzing time and space complexity in the Coding & Algorithms domain.
You are given two jugs with capacities x and y liters and an unlimited water source. You may perform these operations: fill a jug, empty a jug, or pour from one jug to the other until one becomes full or the other becomes empty. Determine whether it is possible to measure exactly z liters in either jug. If it is possible, return true and optionally output one valid sequence of operations; otherwise return false. Describe and analyze both a graph-search approach (e.g., BFS/DFS over states) and a number-theoretic approach (using properties of gcd), including edge cases such as z == 0, z > x + y, and when x or y is 0. Implement canMeasure(x, y, z) and provide time and space complexity.
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.