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
Substring combination in JavaScript
We are required to write a JavaScript function that takes in two strings as the first and the second argument. Let's call these strings str1 and str2. The function should check whether there exists a substring combination in str2, that when combined yields str2.
By substring combination, we mean that we can skip characters but we have to maintain the order of the characters selected from str1.
For example, if the input strings are:
const str1 = 'desxooajmepwele'; const str2 = 'example';
Then the output should be true because the string 'example' can be formed by picking some characters and maintaining their order from str1.
How It Works
The algorithm uses two pointers to traverse both strings. For each character in str2, we search for it in the remaining portion of str1, starting from where we last found a match. If we can find all characters of str2 in order within str1, the function returns true.
Example
const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsString = (str1 = '', str2 = '') => {
let [foundAt, next] = [0, 0];
for (const char of str2) {
next = str1.slice(foundAt).indexOf(char);
if (next === -1) {
return false;
}
foundAt += next + 1;
}
return true;
};
console.log(containsString(str1, str2));
Output
true
Step-by-Step Breakdown
Let's trace through how 'example' is found in 'desxooajmepwele':
const str1 = 'desxooajmepwele';
const str2 = 'example';
const containsStringWithTrace = (str1, str2) => {
let foundAt = 0;
for (let i = 0; i
Output
Tracing character matches:
Found 'e' at position 1
Found 'x' at position 2
Found 'a' at position 6
Found 'm' at position 7
Found 'p' at position 9
Found 'l' at position 13
Found 'e' at position 14
true
Edge Cases
const containsString = (str1 = '', str2 = '') => {
let [foundAt, next] = [0, 0];
for (const char of str2) {
next = str1.slice(foundAt).indexOf(char);
if (next === -1) {
return false;
}
foundAt += next + 1;
}
return true;
};
// Test various cases
console.log('Empty str2:', containsString('hello', '')); // true
console.log('Empty str1:', containsString('', 'hello')); // false
console.log('Same strings:', containsString('hello', 'hello')); // true
console.log('No match:', containsString('abc', 'xyz')); // false
console.log('Partial match:', containsString('programming', 'gram')); // true
Output
Empty str2: true
Empty str1: false
Same strings: true
No match: false
Partial match: true
Conclusion
This substring combination algorithm efficiently checks if one string can be formed as a subsequence of another using a single pass with two pointers. It maintains character order while allowing skipped characters, making it useful for pattern matching and string validation tasks.
