KLA interview questions & answers

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

CodingEasyKLASoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingMediumKLASoftware Engineer

2. LRU Cache (LeetCode)

Model answer

The task

Design a cache with a fixed capacity that supports retrieving and inserting key-value pairs. When an insertion exceeds capacity, evict the item that has gone unused for the longest time.

Key idea

Use a hash map for direct key lookup and a doubly linked list to track recency. Keep the most recently used item at the front; the least recently used item is at the back.

Approach

  1. Create a map from keys to their linked-list nodes.
  2. Use dummy head and tail nodes so items can be added or removed without special cases at the ends.
  3. On a successful get, move the node to the front and return its value; return -1 if the key is absent.
  4. On put, update and promote an existing node, or add a new node at the front.
  5. If the cache is over capacity, remove the node just before the tail and delete its key from the map.
class _Node:
    def __init__(self, key: int = 0, value: int = 0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.nodes = {}

        # Items are stored between these sentinels.
        self.head = _Node()
        self.tail = _Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def _remove(self, node: _Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_to_front(self, node: _Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _make_most_recent(self, node: _Node) -> None:
        self._remove(node)
        self._add_to_front(node)

    def get(self, key: int) -> int:
        node = self.nodes.get(key)
        if node is None:
            return -1

        self._make_most_recent(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        node = self.nodes.get(key)

        if node is not None:
            node.value = value
            self._make_most_recent(node)
            return

        node = _Node(key, value)
        self.nodes[key] = node
        self._add_to_front(node)

        if len(self.nodes) > self.capacity:
            least_recent = self.tail.prev
            self._remove(least_recent)
            del self.nodes[least_recent.key]

Complexity:

  • Time: O(1) for get and put; map and list operations take constant time.
  • Space: O(capacity); the map and list store at most the cache’s capacity of entries.

Common follow-ups

  • How would you make the cache thread-safe? Protect operations with a lock.
  • What if entries expire after a time-to-live? Track expiration times and remove expired entries during access or with a cleanup mechanism.
  • How would you support eviction by frequency instead of recency? Track access counts and organize entries by frequency.
CodingMediumKLASoftware Engineer

3. Maximum Product of First and Last Elements of a Subsequence (LeetCode)

Model answer

The task

Given an array and a subsequence length k, choose a subsequence whose first and last values have the largest possible product. The elements between those endpoints only need to preserve their original order.

Key idea

For a chosen right endpoint, a valid left endpoint must be at least k - 1 positions earlier. As we scan right endpoints, keep the smallest and largest eligible left values; one of these gives the best product, even when values can be negative.

Approach

  1. If k == 1, both endpoints are the same element, so maximize its square.
  2. Scan each possible right endpoint, starting at index k - 1.
  3. Add the newly eligible left value, at index right - (k - 1), to the running minimum and maximum.
  4. Multiply the right value by both extrema and update the best product.
from typing import List

class Solution:
    def maxProduct(self, nums: List[int], k: int) -> int:
        # A one-element subsequence has the same first and last element.
        if k == 1:
            return max(value * value for value in nums)

        min_left = float("inf")
        max_left = float("-inf")
        best = float("-inf")

        # The endpoints must be at least k - 1 indices apart.
        for right in range(k - 1, len(nums)):
            left = right - (k - 1)
            min_left = min(min_left, nums[left])
            max_left = max(max_left, nums[left])

            best = max(
                best,
                nums[right] * min_left,
                nums[right] * max_left,
            )

        return best

Complexity:

  • Time: O(n), scanning the array once.
  • Space: O(1), using only a few running values.

Common follow-ups

  • What if all values are positive? Track only the largest eligible left value.
  • What if the subsequence must have exactly k elements? The same method applies: the endpoint gap must be at least k - 1.
  • What if we need the endpoint indices too? Store the indices associated with the running minimum and maximum and update them with the best product.
CodingMediumKLASoftware Engineer

4. Next Greater Element II (LeetCode)

Model answer

The task

For each position in a circular array, find the first value encountered moving forward that is strictly greater than the value at that position. Return -1 if no such value exists.

Key idea

Use a decreasing monotonic stack of unresolved indices. Scan the array twice to account for wrapping, but add indices to the stack only during the first scan so each position is processed once as a candidate.

Approach

  1. Initialize every answer to -1 and create an empty stack of indices.
  2. Scan positions from 0 to 2 * n - 1, using modulo n to read the circular array.
  3. While the current value is greater than the value at the stack’s top index, record it as that index’s answer and pop the index.
  4. Push the current index only during the first scan.
class Solution:
    def nextGreaterElements(self, nums: list[int]) -> list[int]:
        n = len(nums)
        answer = [-1] * n
        stack = []  # Indices whose next greater value is not yet found.

        for i in range(2 * n):
            index = i % n

            # Resolve earlier indices for which this value is the next greater.
            while stack and nums[stack[-1]] < nums[index]:
                answer[stack.pop()] = nums[index]

            # Add each index only once, during the first pass.
            if i < n:
                stack.append(index)

        return answer

Complexity:

  • Time: O(n), since each index is pushed and popped at most once.
  • Space: O(n), for the answer and stack.

Common follow-ups

  • What changes for a non-circular array? Scan only once, without modulo or the second pass.
  • How would you handle “next greater or equal”? Change the comparison to <=.
  • Can the result be computed in place? It can be done with extra bookkeeping, but a separate answer array is clearer and avoids overwriting values needed for comparisons.
CodingMediumKLASoftware Engineer

5. Brick Wall (LeetCode)

Model answer

The task

Given rows of bricks with equal total width, choose a vertical cut that does not pass through any brick. Return the fewest bricks the cut can cross.

Key idea

A cut at an internal brick boundary avoids crossing bricks in that row. Count how many rows share each internal boundary, then place the cut at the most frequent one.

Approach

  1. Create a counter for internal boundary positions.
  2. For each row, accumulate brick widths from left to right.
  3. Count each cumulative position except the row’s final edge.
  4. Subtract the most frequent boundary count from the number of rows.
  5. If there are no internal boundaries, every cut crosses one brick per row.
from collections import Counter
from typing import List

class Solution:
    def leastBricks(self, wall: List[List[int]]) -> int:
        boundary_counts = Counter()

        for row in wall:
            position = 0

            # Exclude the final edge, since it is the wall's outer boundary.
            for brick_width in row[:-1]:
                position += brick_width
                boundary_counts[position] += 1

        most_common_boundary = max(boundary_counts.values(), default=0)
        return len(wall) - most_common_boundary

Complexity:

  • Time: O(B), where B is the total number of bricks, since each brick is processed at most once.
  • Space: O(E), where E is the number of distinct internal boundary positions recorded.

Common follow-ups

  • What if the wall has no shared internal boundaries? The maximum count is zero, so the cut crosses one brick in every row.
  • How would you return a cut position as well? Track the position whenever its count becomes the new maximum.
  • Does this work if rows have different total widths? Not necessarily; a valid cut must lie within the shared width of all rows.
CodingHardKLASoftware Engineer

6. Find Median from Data Stream (LeetCode)

Model answer

The task

Design a data structure that accepts numbers one at a time and can return the median of all numbers seen so far. The median is the middle value for an odd count, or the average of the two middle values for an even count.

Key idea

Keep the lower half of the values in a max-heap and the upper half in a min-heap. Maintain heap sizes so the lower half has either the same number of elements as the upper half or exactly one more.

Approach

  1. Store the lower half as negated values in Python’s min-heap; store the upper half normally.
  2. Insert each new value into the lower heap.
  3. Move the largest lower-half value to the upper heap to preserve ordering.
  4. If the upper heap becomes larger, move its smallest value back to the lower heap.
  5. Return the lower heap’s top for an odd count, or average the two heap tops for an even count.
import heapq

class MedianFinder:
    def __init__(self):
        # Negated values make this a max-heap.
        self.lower = []
        # A regular min-heap.
        self.upper = []

    def addNum(self, num: int) -> None:
        heapq.heappush(self.lower, -num)

        # Ensure every value in lower is <= every value in upper.
        largest_lower = -heapq.heappop(self.lower)
        heapq.heappush(self.upper, largest_lower)

        # Keep lower the same size as upper, or one element larger.
        if len(self.upper) > len(self.lower):
            smallest_upper = heapq.heappop(self.upper)
            heapq.heappush(self.lower, -smallest_upper)

    def findMedian(self) -> float:
        if len(self.lower) > len(self.upper):
            return float(-self.lower[0])

        return (-self.lower[0] + self.upper[0]) / 2.0

Complexity:

  • Time: addNum is O(log n) due to heap operations; findMedian is O(1).
  • Space: O(n) to store all numbers across the two heaps.

Common follow-ups

  • How would you support removing values? Use lazy deletion with delayed removals, pruning heap tops as needed.
  • What if numbers arrive in a bounded integer range? A frequency array can track counts and locate the middle ranks.
  • Can this be distributed across machines? Maintain ordered partitions or quantile summaries, then combine counts to find the middle ranks.
CodingHardKLASoftware Engineer

7. Maximum Fruits Harvested After at Most K Steps (LeetCode)

Model answer

The task

Given fruit positions and amounts, find the most fruit you can collect when starting at a specified position and walking no more than k steps.

Key idea

The fruit collected can be represented as a contiguous range in position order: any fruit between two visited positions can be collected without extra travel. For a candidate range, compute the shortest route that visits both endpoints, then use a sliding window to keep the range within the step limit.

Approach

  1. Keep a window over the sorted fruit positions and track its total amount.
  2. For endpoints left and right, calculate the shorter route that visits both, starting at startPos.
  3. Extend the right endpoint one fruit at a time.
  4. While the window requires more than k steps, remove its leftmost fruit.
  5. Record the largest total amount seen.
class Solution:
    def maxTotalFruits(self, fruits: list[list[int]], startPos: int, k: int) -> int:
        left = 0
        window_total = 0
        best = 0

        for right, (right_pos, amount) in enumerate(fruits):
            window_total += amount

            while left <= right:
                left_pos = fruits[left][0]
                span = right_pos - left_pos

                # Visit the left endpoint first, or the right endpoint first.
                travel = min(
                    abs(startPos - left_pos) + span,
                    abs(startPos - right_pos) + span,
                )

                if travel <= k:
                    break

                window_total -= fruits[left][1]
                left += 1

            best = max(best, window_total)

        return best

Complexity:

  • Time: O(n), since each fruit enters and leaves the window at most once.
  • Space: O(1), excluding the input.

Common follow-ups

  • What if the fruits are not sorted? Sort by position first, taking O(n log n) time.
  • What if fruit amounts can be negative? The contiguous-range argument and maximum-window tracking need reconsideration.
  • How does the method handle a start position outside the fruit range? The endpoint route calculation naturally reduces to walking toward the farthest endpoint.
CodingHardKLASoftware Engineer

8. Reaching Points (LeetCode)

Model answer

The task

Determine whether a starting pair can be transformed into a target pair by repeatedly adding one coordinate to the other.

Key idea

Reverse the process: subtract the smaller target coordinate from the larger one. Batch repeated subtractions with modulo, as in the Euclidean algorithm. When one coordinate reaches its starting value, check whether the other differs from its start by a multiple of it.

Approach

  1. While both target coordinates are at least their starting values, check whether either coordinate has reached its starting value.
  2. If the first coordinate is fixed, test whether the second can be reduced to its start by repeated subtraction.
  3. Apply the symmetric check if the second coordinate is fixed.
  4. Otherwise, reduce the larger coordinate modulo the smaller.
  5. If either coordinate drops below its start, the target is unreachable.
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while tx >= sx and ty >= sy:
            if tx == sx:
                return (ty - sy) % sx == 0

            if ty == sy:
                return (tx - sx) % sy == 0

            if tx > ty:
                tx %= ty
            else:
                ty %= tx

        return False

Complexity:

  • Time: O(log(max(tx, ty))) modulo steps, as in the Euclidean algorithm.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • What if coordinates can be zero? Handle zero divisors explicitly; modulo-based checks assume positive coordinates.
  • Can you provide a forward search? It branches and may grow rapidly, so reversing with modulo is much more efficient.
  • Why use modulo instead of subtracting once? It batches many identical reverse steps into one operation.

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