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
JavaScript Program for Longest Subsequence of a Number having Same Left and Right Rotation
We will implement a code to find the longest subsequence of a given number that has the same left and right rotation in JavaScript. Left rotation moves the leftmost digit to the rightmost position, while right rotation moves the rightmost digit to the leftmost position.
Understanding the Problem
Given a number, we need to find a subsequence (formed by deleting some digits) where left and right rotations produce the same result. For example:
Single digit sequences always have equal rotations: 1, 2, 3
Two identical digits: 11, 22, 33
Alternating patterns of even length: 1010, 2323, 8989
From the number 100310801, we can extract subsequences like 1010 or 0000 that satisfy this condition.
Naive Approach
The brute force method generates all possible subsequences (2^N for N digits), then checks if each subsequence has equal left and right rotations. This results in O(N × 2^N) time complexity, making it inefficient for numbers with more than 20 digits.
Optimal Approach
The key observation is that valid subsequences must follow an alternating pattern with even length, where positions alternate between two specific digits. We iterate through all possible digit pairs and find the longest alternating subsequence.
Implementation
// Function to find the longest alternating subsequence
function findLongestRotationSubsequence(str) {
const num = str.length;
let maxLength = 0;
// Try all possible pairs of digits (0-9)
for (let i = 0; i {
console.log(`Number: ${test}, Max length: ${findLongestRotationSubsequence(test)}`);
});
Input number: 100310801 Longest subsequence length: 4 Number: 123456, Max length: 1 Number: 111111, Max length: 6 Number: 121212, Max length: 6 Number: 100210601, Max length: 4
Algorithm Analysis
| Approach | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Brute Force | O(N × 2^N) | O(1) | Poor for large inputs |
| Optimal | O(N) | O(1) | Excellent |
Key Points
Valid subsequences must have alternating digit patterns
For different digits, the length must be even
Single repeated digits can form valid subsequences of any length
The algorithm checks all 100 possible digit pairs (0-9 × 0-9)
Conclusion
The optimal solution efficiently finds the longest subsequence with equal left and right rotations in O(N) time. By recognizing the alternating pattern requirement, we avoid the exponential complexity of generating all possible subsequences.
