Wormhole Route Combinations — Problem Statement & Solution Guide

RecursionMediumMixed
TimeO(n)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Recursion and solve the Wormhole Route Combinations problem optimally.

TopicRecursion
PatternMixed
TimeO(n)
SpaceO(1)

Problem Description

Given a positive integer n representing the total distance to be covered, compute the number of distinct sequences of moves that exactly sum to n when each move can be either a single‑unit step or a double‑unit step. Two sequences are considered different if the order of the 1‑step and 2‑step moves differs. The result should be returned as an integer.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Wormhole Route Combinations"

medium

WHY DOES IT MATTER?

The 1‑step/2‑step pattern captures the essence of linear recurrence relations, a building block for many combinatorial counting problems and for understanding dynamic programming fundamentals.

OPTIMIZATION CHALLENGE

The key insight is recognizing overlapping sub‑problems and replacing the exponential recursion with a linear recurrence that can be solved iteratively or via matrix exponentiation, drastically cutting time and space.

REAL-WORLD CONNECTION

Think of a data packet traversing a network where each hop can be a short or long link; counting distinct routes mirrors the same recurrence, helping engineers model latency and routing options.

During an interview, write the recurrence first, then immediately switch to a bottom‑up loop with two rolling variables—this shows you understand both the theory and the practical space optimization.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem is a classic example of counting the number of ways to tile a 1×n board with 1×1 and 1×2 tiles, which maps directly to the Fibonacci sequence. A naive recursive solution explores every possible combination of 1‑step and 2‑step moves, leading to an exponential blow‑up because the same sub‑problems are recomputed many times. By recognizing that the number of ways to reach distance n equals ways(n‑1)+ways(n‑2), we can apply dynamic programming or memoization to store intermediate results, turning the exponential recursion into a linear‑time solution. This optimal paradigm leverages overlapping sub‑problems and optimal substructure, the two hallmarks of dynamic programming, and yields an O(n) time and O(1)‑or‑O(n) space algorithm depending on implementation.

Interview Questions on This Problem

Q1How would you modify the solution if a 3‑unit step were also allowed?

The recurrence becomes ways(n)=ways(n‑1)+ways(n‑2)+ways(n‑3); you can extend the DP array or rolling variables accordingly, still O(n) time.

Q2What is the time‑space trade‑off between a memoized recursive solution and an iterative DP for this problem?

Memoized recursion uses O(n) stack space plus O(n) memo table, while the iterative version can reduce space to O(1) by keeping only the last two values, both run in O(n) time.

Q3In a distributed system, how could you parallelize the computation of the nth Fibonacci‑like value without violating the dependency order?

You can compute independent sub‑ranges using matrix exponentiation or fast doubling, which reduces the problem to O(log n) time with parallelizable multiplications, but the classic DP cannot be parallelized because each state depends on the two previous ones.

Examples

Example 1

Input

1

Output

1

Explanation: Only one possible move: a single‑unit step (1). Hence exactly one route.

Example 2

Input

3

Output

3

Explanation: The distance 3 can be achieved by: (1,1,1), (1,2), and (2,1). These are three distinct ordered sequences, so the answer is 3.

Example 3

Input

5

Output

8

Explanation: All ordered combinations of 1‑ and 2‑steps that sum to 5 are: (1,1,1,1,1), (1,1,1,2), (1,1,2,1), (1,2,1,1), (2,1,1,1), (1,2,2), (2,1,2), (2,2,1). There are 8 such routes, which matches the 6th Fibonacci number.

Constraints

  • 1 <= n <= 10^5
  • Result fits within a 64‑bit signed integer

Optimal Approach & Strategy

Use a bottom‑up DP or two‑variable iteration that builds the answer from 0 to n using the recurrence ways(i)=ways(i‑1)+ways(i‑2).

Brute Force Approach

Recursively try every combination of 1‑step and 2‑step moves, returning 1 when the sum equals n and 0 when it exceeds n.

Code Solutions

JavaScript Solution
Time: O(n)
function countWays(n){
    if(n<0) return 0;
    if(n===0) return 1;
    let a=1, b=1; // dp[0]=1, dp[1]=1
    for(let i=2;i<=n;i++){
        const c=a+b;
        a=b;
        b=c;
    }
    return b;
}
const fs=require('fs');
const input=fs.readFileSync(0,'utf8').trim();
const n=parseInt(input,10);
console.log(countWays(n));

Asked in Top Tech Interviews

Infosys

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.