Rakuten interview questions & answers

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

CodingEasyRakutenSoftware Engineer

1. Climbing Stairs (LeetCode)

Model answer

The task

Count how many distinct ways there are to reach the top of a staircase with n steps when each move advances either one or two steps.

Key idea

To reach step i, the last move must come from step i - 1 or i - 2. Thus the number of ways to reach i is the sum of the ways to reach those two earlier steps. Only the previous two counts are needed, so there is no need to store a full table.

Approach

  1. Set the number of ways to reach step 0 to 1, representing the single empty sequence of moves.
  2. Set the number of ways to reach step 1 to 1.
  3. For each step from 2 through n, add the counts for the preceding two steps.
  4. Return the count for step n.
class Solution:
    def climbStairs(self, n: int) -> int:
        # Ways to reach steps 0 and 1.
        two_back = 1
        one_back = 1

        # Build the count using the two preceding results.
        for _ in range(2, n + 1):
            current = two_back + one_back
            two_back = one_back
            one_back = current

        return one_back

Complexity:

  • Time: O(n), since each step is processed once.
  • Space: O(1), since only two prior counts are retained.

Common follow-ups

  • What if each move can advance 1, 2, or 3 steps? Sum the counts for the previous three steps.
  • What if the result must be returned modulo a number? Apply the modulus after each addition.
  • What if some steps are forbidden? Set their ways count to zero and use dynamic programming for the allowed steps.
CodingMediumRakutenSoftware Engineer

2. Rotting Oranges (LeetCode)

Model answer

The task

Given a grid of empty cells, fresh oranges, and rotten oranges, find the minimum number of minutes until no fresh oranges remain. Each minute, a rotten orange makes any fresh orange directly above, below, left, or right of it rotten; return -1 if some fresh oranges can never be reached.

Key idea

Use multi-source breadth-first search: all initially rotten oranges spread at the same time, so put them all in the queue at the start. Process the queue one minute at a time, counting newly rotten oranges to detect whether any fresh ones remain unreachable.

Approach

  1. Count the fresh oranges and enqueue every initially rotten orange.
  2. If there are no fresh oranges, return 0.
  3. For each BFS layer, rot adjacent fresh oranges, decrement the fresh count, and enqueue them.
  4. Count each processed layer as one minute.
  5. Return the minutes if all fresh oranges rotted; otherwise return -1.
from collections import deque
from typing import List

class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        queue = deque()
        fresh = 0

        # Gather all initial sources and count oranges that still need to rot.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 2:
                    queue.append((r, c))
                elif grid[r][c] == 1:
                    fresh += 1

        if fresh == 0:
            return 0

        minutes = 0
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while queue and fresh > 0:
            # Process exactly the oranges rotten before this minute began.
            for _ in range(len(queue)):
                r, c = queue.popleft()

                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if (
                        0 <= nr < rows
                        and 0 <= nc < cols
                        and grid[nr][nc] == 1
                    ):
                        grid[nr][nc] = 2
                        fresh -= 1
                        queue.append((nr, nc))

            minutes += 1

        return minutes if fresh == 0 else -1

Complexity:

  • Time: O(rows × cols), since each cell is visited at most once.
  • Space: O(rows × cols) for the BFS queue in the worst case.

Common follow-ups

  • What if diagonal neighbors also spread rot? Add the four diagonal directions to the neighbor list.
  • Can the original grid be preserved? Copy it first, or track visited cells separately.
  • How would you return which oranges rot each minute? Store each BFS layer’s cells or record a rot-time value per cell.
CodingMediumRakutenSoftware Engineer

3. Combination Sum II (LeetCode)

Model answer

The task

Given a list of positive integers that may contain duplicates, find all distinct combinations summing to a target. Each list element can be used at most once.

Key idea

Sort the numbers so equal values are adjacent and values larger than the remaining target can be skipped. During one recursive step, skip equal values already tried at that same depth; this avoids duplicate combinations without blocking equal values at later depths.

Approach

  1. Sort the input.
  2. Recursively build a combination, tracking the next available index and remaining sum.
  3. When the remaining sum reaches zero, save a copy of the combination.
  4. For each candidate, skip duplicates at the current depth and stop once the candidate exceeds the remaining sum.
  5. Recurse from the next index so each element is used at most once.
class Solution:
    def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:
        candidates.sort()
        results = []
        combination = []

        def backtrack(start: int, remaining: int) -> None:
            if remaining == 0:
                results.append(combination.copy())
                return

            for i in range(start, len(candidates)):
                # Try each distinct value only once at this recursion depth.
                if i > start and candidates[i] == candidates[i - 1]:
                    continue

                value = candidates[i]
                # Sorting means all later values are too large as well.
                if value > remaining:
                    break

                combination.append(value)
                backtrack(i + 1, remaining - value)
                combination.pop()

        backtrack(0, target)
        return results

Complexity:

  • Time: O(n · 2^n) in the worst case, accounting for exploring subsets and copying saved combinations.
  • Space: O(n) auxiliary space for the recursion and current combination; result storage is excluded.

Common follow-ups

  • What if candidates can be reused? Recurse from i rather than i + 1.
  • How can the search be pruned further? Precompute suffix sums to rule out branches whose available values cannot reach the remaining target.
  • How would you avoid storing every result? Use a generator or callback to emit each combination as it is found.
CodingMediumRakutenSoftware Engineer

4. 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.
CodingMediumRakutenSoftware Engineer

5. String Compression (LeetCode)

Model answer

The task

Compress consecutive runs of identical characters in a character array, modifying it in place. Keep one character per run and append the run’s count as decimal digits when it is greater than one; return the length of the compressed prefix.

Key idea

Use one pointer to scan each run and another to write the compressed result. Since the write pointer never moves ahead of the read pointer, writing the result cannot overwrite characters that are still needed.

Approach

  1. Start read and write pointers at the beginning of the array.
  2. For each run, remember its character and count its length.
  3. Write the character at the next output position.
  4. If the run has multiple characters, write its count one digit at a time.
  5. Return the final write position.
from typing import List

class Solution:
    def compress(self, chars: List[str]) -> int:
        read = 0
        write = 0
        n = len(chars)

        while read < n:
            char = chars[read]
            run_start = read

            while read < n and chars[read] == char:
                read += 1

            count = read - run_start
            chars[write] = char
            write += 1

            if count > 1:
                # Find the highest power of ten in the count.
                divisor = 1
                while divisor <= count // 10:
                    divisor *= 10

                # Write the count's digits from most to least significant.
                while divisor > 0:
                    digit = (count // divisor) % 10
                    chars[write] = str(digit)
                    write += 1
                    divisor //= 10

        return write

Complexity:

  • Time: O(n), since each character is scanned once and the output has at most O(n) digits.
  • Space: O(1) auxiliary space; the array is modified in place.

Common follow-ups

  • What if counts use a different base? Find the digits in that base and write them from most significant to least.
  • What if the input cannot be modified? Build and return a separate output sequence.
  • What if runs are streamed and the input is unbounded? Retain the current character and count, emitting each run when it ends.
CodingMediumRakutenSoftware Engineer

6. Longest Substring Without Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous section of a string in which every character appears at most once.

Key idea

Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.

Approach

  1. Track each character’s most recent index in a dictionary.
  2. Keep left as the window’s starting index and best as its longest length so far.
  3. For each character, move left forward if its previous occurrence is inside the current window.
  4. Record the character’s current index and update best using the window length.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last_seen = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            # Skip past a repeated character if it is in the current window.
            if char in last_seen and last_seen[char] >= left:
                left = last_seen[char] + 1

            last_seen[char] = right
            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), because each character is processed once.
  • Space: O(k), where k is the number of distinct characters encountered.

Common follow-ups

  • Return the substring itself: store the best window’s start and end indices when updating best.
  • Handle a stream of characters: keep the same window state and process each arriving character incrementally.
  • Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
CodingMediumRakutenSoftware Engineer

7. Rotate Image (LeetCode)

Model answer

The task

Rotate a square matrix 90 degrees clockwise, modifying the matrix in place.

Key idea

A clockwise rotation can be split into two operations: transpose the matrix, then reverse each row. Together, these move every value to its rotated position without allocating another matrix.

Approach

  1. Transpose the matrix by swapping entries across its main diagonal.
  2. Visit each row and reverse it in place.
  3. Return nothing; the input matrix holds the result.
class Solution:
    def rotate(self, matrix: list[list[int]]) -> None:
        n = len(matrix)

        # Transpose across the main diagonal.
        for row in range(n):
            for col in range(row + 1, n):
                matrix[row][col], matrix[col][row] = (
                    matrix[col][row],
                    matrix[row][col],
                )

        # Reverse each row to complete the clockwise rotation.
        for row in matrix:
            row.reverse()

Complexity:

  • Time: O(n²), since each matrix entry is processed a constant number of times.
  • Space: O(1), because the rotation is performed in place.

Common follow-ups

  • How would you rotate 90 degrees counterclockwise? Transpose, then reverse each column instead of each row.
  • How would you rotate 180 degrees? Reverse the order of rows and reverse each row.
  • What if the matrix is not square? A rectangular matrix generally cannot be rotated in place without changing its dimensions; use a new matrix or a more involved cycle-based method when dimensions permit.
CodingHardRakutenSoftware Engineer

8. Trapping Rain Water (LeetCode)

Model answer

The task

Given an array of nonnegative bar heights, compute how much water remains trapped between the bars after rainfall. Each bar has unit width.

Key idea

Water above a position is limited by the shorter of the tallest bars to its left and right. With two pointers, process the side whose current height is lower: its boundary already determines the maximum water that position can hold, so no arrays of prefix and suffix maxima are needed.

Approach

  1. Start pointers at both ends and track the greatest height seen from each side.
  2. While the pointers have not crossed, compare their current heights.
  3. If the left height is lower, update the left maximum and add any water above the left bar, then advance the left pointer.
  4. Otherwise, do the symmetric operation on the right.
  5. Return the accumulated water.
from typing import List

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = 0
        water = 0

        while left < right:
            if height[left] < height[right]:
                # The right side is tall enough that the left maximum
                # determines the water level at this position.
                left_max = max(left_max, height[left])
                water += left_max - height[left]
                left += 1
            else:
                # Symmetrically, the right maximum determines this level.
                right_max = max(right_max, height[right])
                water += right_max - height[right]
                right -= 1

        return water

Complexity:

  • Time: O(n), because each pointer moves across the array at most once.
  • Space: O(1), because the algorithm uses only a fixed number of variables.

Common follow-ups

  • How can this be solved with dynamic programming? Precompute the maximum height to each position from the left and right, then sum the trapped water at each position.
  • How can a monotonic stack solve it? Keep indices of decreasing bar heights; when a taller bar arrives, pop a basin bottom and calculate the bounded layer.
  • What if bars have different widths? Track each bar’s width and use area rather than unit-width contributions; the boundary logic must account for the resulting horizontal spans.

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