Good morning! Here's our prompt for today.
Given two strings, one named sub
and the other str
, determine if sub
is a subsequence of str
.
JAVASCRIPT
1const str = "barbell"
2const sub = "bell"
3isASubsequence(sub, str);
4// true
For the sake of the exercise, let's assume that these strings only have lower case characters.
What is subsequence? You can think of it as a substring, but the letters don't have to be adjacent. It is formed from the base string by deleting some or none of the characters without affecting the relative positions of the other letters. So this also works:
JAVASCRIPT
1const str = "chicken"
2const sub = "hen"
3isASubsequence(sub, str);
4// true
Constraints
- Length of both the strings <=
100000
- The strings will contain only alphanumeric characters (
a-z , A-Z, 0-9
) - The strings can be empty
- Expected time complexity :
O(n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
56
var assert = require('assert');
/**
* @param {string} sub
* @param {string} str
* @return {boolean}
*/
function isASubsequence(sub, str) {
// fill this in
return true;
}
try {
assert.deepEqual(isASubsequence('c', 'co'), true);
console.log('PASSED: ' + "isASubsequence('c','co') should return true");
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(isASubsequence('liblu', 'egi'), false);
console.log('PASSED: ' + "isASubsequence('liblu','egi') should return false");
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(isASubsequence('ej', 'sej'), true);
console.log('PASSED: ' + "isASubsequence('ej','sej') should return true");
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(isASubsequence('zumkidin', 'hu'), false);
console.log(
'PASSED: ' + "isASubsequence('zumkidin','hu') should return false"
);
} catch (err) {
console.log(err);
}
try {
assert.deepEqual(isASubsequence('eviazauli', 'de'), false);
console.log(
'PASSED: ' + "isASubsequence('eviazauli','de') should return false"
);
} catch (err) {
console.log(err);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.