Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Unique substrings in circular string in JavaScript
Problem
Suppose we have a S, str. which is an infinite wraparound string of the string −
"abcdefghijklmnopqrstuvwxyz".
Therefore, S will look like this −
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
We are required to write a JavaScript function that takes in str, let’s call that string str, as the only argument.
Our function should find out how many unique non-empty substrings of str are present in S.
Our function should finally return the number of different non-empty substrings of str in the string S.
For example, if the input to the function is −
const str = "zab";
Then the output should be −
const output = 6;
Output Explanation
There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string S.
Example
The code for this will be −
const str = "zab";
const allSubstrings = (str = '') => {
const dp = new Array(26).fill(0);
dp[str.charCodeAt(0) - 97] = 1;
maxCount = 1;
for (let i = 1; i < str.length; i++) {
if ((str.charCodeAt(i) - str.charCodeAt(i - 1) == 1) || (str.charCodeAt(i) - str.charCodeAt(i - 1) == -25)) {
maxCount++;
} else {
maxCount = 1;
}
dp[str.charCodeAt(i) - 97] = Math.max(dp[str.charCodeAt(i) - 97], maxCount);
}
return dp.reduce((item, val) => {
return val + item;
})
};
console.log(allSubstrings(str));
Output
And the output in the console will be −
6
Advertisements