BackmediumRecursionInfosys

Wormhole Route Combinations Solution

Problem Statement

Given a target distance, determine the total number of distinct routes that can be formed by taking either a single unit or a pair of units at a time.

Example 1
Input
targetDistance = 4, stepSizes = [1, 2]
Output
5

Explanation: Step-by-step: We can form the following routes: (1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 3), (2, 1, 1).

Example 2
Input
targetDistance = 5, stepSizes = [1, 2]
Output
7

Explanation: Step-by-step: We can form the following routes: (1, 1, 1, 1, 1), (1, 1, 2, 1), (1, 1, 3), (1, 2, 1, 1), (1, 2, 2), (1, 3, 1), (2, 1, 1, 1).

Constraints

  • Input will be a positive integer
  • Input will not exceed 40
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Wormhole Route Combinations — Problem Statement & Solution Guide

RecursionMediumMixed
TimeO(n)
|
SpaceO(1)

Problem Description

Given a target distance, determine the total number of distinct routes that can be formed by taking either a single unit or a pair of units at a time.

Examples

Example 1

Input

targetDistance = 4, stepSizes = [1, 2]

Output

5

Explanation: Step-by-step: We can form the following routes: (1, 1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 3), (2, 1, 1).

Example 2

Input

targetDistance = 5, stepSizes = [1, 2]

Output

7

Explanation: Step-by-step: We can form the following routes: (1, 1, 1, 1, 1), (1, 1, 2, 1), (1, 1, 3), (1, 2, 1, 1), (1, 2, 2), (1, 3, 1), (2, 1, 1, 1).

Constraints

  • Input will be a positive integer
  • Input will not exceed 40

Optimal Approach & Strategy

The optimal approach uses dynamic programming to store and reuse the results of sub-problems, reducing the time complexity to linear and making it efficient for larger inputs.

Brute Force Approach

The brute-force approach would involve recursively trying all possible combinations of one and two wormholes until reaching the target, but this would result in exponential time complexity and be inefficient for larger inputs.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function wormholeRouteCombinations(targetDistance) {
  if (targetDistance < 0) return 0;
  if (targetDistance === 0) return 1;
  let a = 1, b = 1;
  for (let i = 2; i <= targetDistance; i++) {
    let temp = a + b;
    a = b;
    b = temp;
  }
  let result = 0;
  for (let i = 0; i <= targetDistance; i++) {
    result += Math.floor(targetDistance / i);
  }
  return result;
}

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.