Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding nth element of an increasing sequence using JavaScript
Consider an increasing sequence which is defined as follows:
- The number seq(0) = 1 is the first one in seq.
- For each x in seq, then y = 2 * x + 1 and z = 3 * x + 1 must be in seq too.
- There are no other numbers in seq.
Therefore, the first few terms of this sequence will be:
[1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
We are required to write a function that takes in a number n and returns the nth term of this sequence.
How the Sequence Works
Starting with 1, each number generates two new numbers:
- From 1: 2*1+1=3 and 3*1+1=4
- From 3: 2*3+1=7 and 3*3+1=10
- From 4: 2*4+1=9 and 3*4+1=13
The algorithm maintains the sequence in sorted order by comparing candidates from both formulas.
Solution
const num = 10;
const findNth = n => {
let seq = [1], x = 0, y = 0;
for (let i = 0; i < n; i++) {
let nextX = 2 * seq[x] + 1;
let nextY = 3 * seq[y] + 1;
if (nextX <= nextY) {
seq.push(nextX);
x++;
if (nextX == nextY) {
y++; // Skip duplicate
}
} else {
seq.push(nextY);
y++;
}
}
return seq[n];
};
console.log("10th element:", findNth(num));
console.log("First 12 elements:", seq.slice(0, 12));
Output
10th element: 22
Step-by-Step Example
Let's trace how the sequence builds:
const buildSequence = (count) => {
let seq = [1], x = 0, y = 0;
console.log("Start: seq =", seq);
for (let i = 0; i < count; i++) {
let nextX = 2 * seq[x] + 1;
let nextY = 3 * seq[y] + 1;
if (nextX <= nextY) {
seq.push(nextX);
console.log(`Step ${i+1}: Added ${nextX} (from 2*${seq[x]}+1)`);
x++;
if (nextX == nextY) y++;
} else {
seq.push(nextY);
console.log(`Step ${i+1}: Added ${nextY} (from 3*${seq[y]}+1)`);
y++;
}
}
return seq;
};
buildSequence(5);
Start: seq = [1] Step 1: Added 3 (from 2*1+1) Step 2: Added 4 (from 3*1+1) Step 3: Added 7 (from 2*3+1) Step 4: Added 9 (from 2*4+1) Step 5: Added 10 (from 3*3+1)
Key Points
- Two pointers (x, y) track positions for generating next candidates
- Always choose the smaller candidate to maintain sorted order
- Skip duplicates when both formulas produce the same number
- Time complexity: O(n), Space complexity: O(n)
Conclusion
This algorithm efficiently generates the nth element of the sequence by maintaining sorted order using two pointers. It ensures no duplicates while building the sequence incrementally.
Advertisements
