OYO interview questions & answers

8 real OYO interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (8 OYO questions in total).

CodingEasyOYOSoftware Engineer

1. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingEasyOYOSoftware Engineer

2. Move Zeroes (LeetCode)

Model answer

The task

Rearrange an integer array in place so all zeroes come after the nonzero values. Keep the nonzero values in their original relative order.

Key idea

Use a write pointer to mark where the next nonzero value belongs. Scan the array once, swapping each nonzero value into that position; this keeps the nonzero values stable and uses constant extra space.

Approach

  1. Set write to the first available position for a nonzero value.
  2. Scan each index from left to right.
  3. When a nonzero value is found, swap it with the value at write.
  4. Advance write after each nonzero value.
  5. Once the scan ends, all remaining positions contain zeroes.
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        # The next nonzero value belongs at index write.
        write = 0

        for read in range(len(nums)):
            if nums[read] != 0:
                nums[write], nums[read] = nums[read], nums[write]
                write += 1

Complexity:

  • Time: O(n), where n is the array length; each value is examined once.
  • Space: O(1), since rearrangement is done in place.

Common follow-ups

  • What if relative order does not matter? Partitioning zeroes and nonzeroes can be done with two pointers, potentially with fewer assignments.
  • Can you reduce unnecessary writes? Swap only when read != write; this avoids self-swaps.
  • What if the input is a linked list? Relink nonzero nodes in their original order, then append the zero-valued nodes.
CodingMediumOYOSoftware Engineer

3. House Robber III (LeetCode)

Model answer

The task

Given a binary tree where each node holds a nonnegative amount, choose nodes to maximize the total without choosing both a node and its parent.

Key idea

For each subtree, track two values: the best total if its root is robbed, and the best total if its root is skipped. This lets each parent combine its children’s results without needing to revisit nodes.

Approach

  1. Use depth-first search to compute the two values for each node.
  2. If the node is robbed, its children must be skipped.
  3. If the node is skipped, each child can be robbed or skipped, whichever yields more.
  4. Return the larger of the two values for the tree’s root.
# LeetCode provides the TreeNode class.

class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode]) -> tuple[int, int]:
            # Return (best total if robbed, best total if skipped).
            if node is None:
                return 0, 0

            left_robbed, left_skipped = dfs(node.left)
            right_robbed, right_skipped = dfs(node.right)

            # Rob this node only if both children are skipped.
            robbed = node.val + left_skipped + right_skipped

            # If skipping this node, choose the best option per child.
            skipped = (
                max(left_robbed, left_skipped)
                + max(right_robbed, right_skipped)
            )

            return robbed, skipped

        return max(dfs(root))

Complexity:

  • Time: O(n), where n is the number of nodes, since each node is processed once.
  • Space: O(h), for the recursion stack, where h is the tree height.

Common follow-ups

  • What if the tree is highly unbalanced? The recursion stack can grow to O(n); an iterative postorder traversal avoids recursion-depth issues.
  • What if some node values are negative? The same recurrence works; skipping a negative-valued node can be better than robbing it.
  • Can the result be computed with less memory? The two values per node are already constant-size; the recursion stack is the main extra space.
CodingMediumOYOSoftware Engineer

4. Furthest Building You Can Reach (LeetCode)

Model answer

The task

Given building heights and a limited number of bricks and ladders, find the last building you can reach in order. Bricks cover upward climbs one unit at a time; a ladder can cover any one upward climb.

Key idea

Use ladders for the largest climbs and bricks for the smaller ones. A min-heap tracks climbs tentatively assigned to ladders; whenever there are too many, spend bricks on the smallest climb.

Approach

  1. Visit each consecutive pair of buildings and calculate the upward climb.
  2. Ignore level or downward moves.
  3. Add each positive climb to a min-heap.
  4. If the heap has more climbs than available ladders, use bricks for its smallest climb.
  5. If bricks run out, return the building before that climb; otherwise return the final building.
import heapq
from typing import List

class Solution:
    def furthestBuilding(
        self, heights: List[int], bricks: int, ladders: int
    ) -> int:
        ladder_climbs = []

        for i in range(len(heights) - 1):
            climb = heights[i + 1] - heights[i]

            if climb <= 0:
                continue

            heapq.heappush(ladder_climbs, climb)

            # Keep ladders for the largest climbs seen so far.
            if len(ladder_climbs) > ladders:
                bricks -= heapq.heappop(ladder_climbs)

                if bricks < 0:
                    return i

        return len(heights) - 1

Complexity:

  • Time: O(n log(min(n, ladders + 1))) — each positive climb may be added to or removed from the heap.
  • Space: O(min(n, ladders + 1)) — the heap stores at most the ladder allowance plus one climb.

Common follow-ups

  • Why is this greedy choice optimal? For any set of climbs, assigning ladders to the largest ones minimizes the bricks spent.
  • What if the route must also be reported? Record the climb-to-resource assignments as each step is processed.
  • What if resources change during the route? Update the heap and remaining bricks according to the new resource rules; the simple greedy argument may need to be re-established.
CodingMediumOYOSoftware Engineer

5. Koko Eating Bananas (LeetCode)

Model answer

The task

Given pile sizes and a fixed number of hours, find the smallest integer eating speed that lets Koko finish all the bananas in time. Each pile is handled separately, and any leftover bananas in a pile still take a full hour.

Key idea

Feasibility is monotonic: if a speed works, any faster speed works too. Binary-search the range from 1 to the largest pile, checking each candidate speed by summing the hours needed for every pile.

Approach

  1. Set the search bounds to 1 and the largest pile size.
  2. For a candidate speed, compute each pile’s hours with ceiling division: (pile + speed - 1) // speed.
  3. If the total hours fit within the limit, record the speed and search lower.
  4. Otherwise, search higher.
  5. Return the smallest feasible speed.
class Solution:
    def minEatingSpeed(self, piles: list[int], h: int) -> int:
        left, right = 1, max(piles)

        while left < right:
            speed = (left + right) // 2

            # Check whether this speed finishes all piles in time.
            hours = sum((pile + speed - 1) // speed for pile in piles)

            if hours <= h:
                right = speed
            else:
                left = speed + 1

        return left

Complexity:

  • Time: O(n log m), where n is the number of piles and m is the largest pile; each binary-search check scans the piles.
  • Space: O(1), excluding the input; the check uses only a constant amount of extra space.

Common follow-ups

  • What if the hours limit is smaller than the number of piles? No speed can finish in time, since each nonempty pile takes at least one hour.
  • Can the search bounds be tightened? A lower bound can be derived from total bananas divided by available hours, rounded up.
  • What if piles can be processed in parallel? The feasibility calculation changes to account for concurrent work; this binary search applies when piles are eaten sequentially.
CodingMediumOYOSoftware Engineer

6. Movement of Robots (LeetCode)

Model answer

The task

Given robot positions, their directions, and a shared travel time, compute the sum of distances between every pair of robots at the end, modulo \(10^9+7\).

Key idea

Robots that collide and bounce can be treated as if they pass through each other: this preserves the multiset of final positions, which is all the pairwise-distance sum needs. Compute each resulting position, sort them, then use a prefix sum to total distances efficiently.

Approach

  1. For each robot, add or subtract the travel time from its position according to its direction.
  2. Sort the resulting positions.
  3. Visit them in order, using the prefix sum to add each position’s distance from all earlier positions.
  4. Return the total modulo \(10^9+7\).
from typing import List

class Solution:
    def sumDistance(self, nums: List[int], s: str, d: int) -> int:
        mod = 10**9 + 7

        # Treat collisions as robots passing through each other.
        positions = [
            position + (d if direction == "R" else -d)
            for position, direction in zip(nums, s)
        ]
        positions.sort()

        total = 0
        prefix_sum = 0

        # For a sorted position x, each earlier position contributes x - earlier.
        for i, x in enumerate(positions):
            total += i * x - prefix_sum
            prefix_sum += x

        return total % mod

Complexity:

  • Time: O(n log n), due to sorting the final positions.
  • Space: O(n), for the list of final positions.

Common follow-ups

  • What if the requested quantity is the sum of squared pairwise distances? Use prefix sums of both positions and their squares.
  • What if robots need to be tracked by identity after collisions? Track collision events and swap identities at each collision.
  • How are coincident final positions handled? They contribute zero distance, and the sorted-prefix calculation handles them naturally.
CodingMediumOYOSoftware Engineer

7. Copy List with Random Pointer (LeetCode)

Model answer

The task

Create a deep copy of a linked list whose nodes have both a next pointer and a random pointer. The copy must use new nodes and preserve the links between corresponding nodes.

Key idea

Use a hash map from each original node to its copy. Once every copy exists, use the map to assign each copied node’s next and random links.

Approach

  1. If the head is None, return None.
  2. Traverse the original list and create a copy of each node, recording each original-to-copy mapping.
  3. Traverse again and set each copied node’s links using the map.
  4. Return the copy of the original head.
class Solution:
    def copyRandomList(self, head):
        if head is None:
            return None

        copies = {}
        current = head

        # Create a separate node for every original node.
        while current:
            copies[current] = Node(current.val)
            current = current.next

        # Reconnect the copied nodes using the original links.
        current = head
        while current:
            copied = copies[current]
            copied.next = copies.get(current.next)
            copied.random = copies.get(current.random)
            current = current.next

        return copies[head]

Complexity:

  • Time: O(n), for two traversals of the list.
  • Space: O(n), for the map of original nodes to copies.

Common follow-ups

  • Can you use O(1) extra space? Interleave copied nodes with originals, assign random links, then separate the two lists.
  • What if a random pointer can point outside the list? Ensure the copy strategy also creates and maps every reachable node.
  • How do you verify the result is a deep copy? Check that corresponding values and links match, but no copied node is identical to an original node.
CodingHardOYOSoftware Engineer

8. Merge k Sorted Lists (LeetCode)

Model answer

The task

Combine several individually sorted linked lists into one sorted linked list. The result should reuse the input nodes rather than create a new node for every value.

Key idea

Keep the first unmerged node from each nonempty list in a min-heap. Repeatedly take the smallest node, append it to the result, and add its successor to the heap.

Approach

  1. Add each nonempty list’s head to the heap.
  2. Include a unique counter in each heap entry so equal values never require comparing nodes.
  3. Pop the smallest node and append it to the result.
  4. If that node has a successor, push the successor into the heap.
  5. Return the node after a dummy head.
import heapq
from typing import Optional

class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next

class Solution:
    def mergeKLists(
        self, lists: list[Optional[ListNode]]
    ) -> Optional[ListNode]:
        heap = []
        serial = 0  # Break ties without comparing ListNode objects.

        for node in lists:
            if node is not None:
                heapq.heappush(heap, (node.val, serial, node))
                serial += 1

        dummy = ListNode()
        tail = dummy

        while heap:
            _, _, node = heapq.heappop(heap)
            tail.next = node
            tail = node

            if node.next is not None:
                heapq.heappush(heap, (node.next.val, serial, node.next))
                serial += 1

        tail.next = None
        return dummy.next

Complexity:

  • Time: O(N log k), where each of the N nodes is pushed and popped once.
  • Space: O(k) for the heap, which holds at most one node per input list.

Common follow-ups

  • How can divide and conquer solve this? Merge lists in pairs over successive rounds, also taking O(N log k) time.
  • What if the lists are supplied as a stream? Keep one current node per active list in the heap and add lists as they arrive.
  • Can the inputs be modified? Yes; this solution relinks and reuses their nodes.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions