Skip to content

Commit a97d150

Browse files
committed
update palindrome substrings and encode decode string algorithms
1 parent e1484e8 commit a97d150

File tree

4 files changed

+121
-92
lines changed

4 files changed

+121
-92
lines changed
Lines changed: 41 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,47 @@
1-
//Expand around center:- TC:O(n*2) SC:O(1)
2-
1+
/**
2+
* TC:O(n*2) SC:O(1)
3+
* Counts the number of palindromic substrings in a given string using expand-around-center.
4+
* @param {string} str
5+
* @returns {number}
6+
*/
37
function countPalindromicSubstrings(str) {
4-
5-
if(str.length < 2) return str.length;
6-
7-
let count = 0;
8-
for(let i=0; i< str.length; i++) {
9-
count += countPalindromes(str, i, i);
10-
count += countPalindromes(str, i, i+1);
11-
}
12-
return count;
8+
if (!str || str.length < 1) return 0;
9+
let count = 0;
10+
for (let i = 0; i < str.length; i++) {
11+
count += expandAroundCenter(str, i, i); // Odd length palindromes
12+
count += expandAroundCenter(str, i, i + 1); // Even length palindromes
13+
}
14+
return count;
1315
}
1416

15-
function countPalindromes(str, left, right) {
16-
let count = 0;
17-
while(left >=0 && right < str.length && str[left] === str[right]) {
18-
count++;
19-
left--;
20-
right++;
21-
}
22-
return count;
17+
/**
18+
* Expands around the given center and counts palindromic substrings.
19+
* @param {string} str
20+
* @param {number} left
21+
* @param {number} right
22+
* @returns {number}
23+
*/
24+
function expandAroundCenter(str, left, right) {
25+
let count = 0;
26+
while (left >= 0 && right < str.length && str[left] === str[right]) {
27+
count++;
28+
left--;
29+
right++;
30+
}
31+
return count;
2332
}
2433

25-
let str = "baaab";
26-
console.log(countPalindromicSubstrings(str));
34+
// Test cases
35+
const testCases = [
36+
{ str: "baaab", expected: 9 },
37+
{ str: "abcd", expected: 4 },
38+
{ str: "aaa", expected: 6 },
39+
{ str: "", expected: 0 },
40+
{ str: "a", expected: 1 },
41+
{ str: "abccba", expected: 9 },
42+
];
2743

28-
let str1 = "abcd";
29-
console.log(countPalindromicSubstrings(str1));
30-
31-
let str2 = "aaa";
32-
console.log(countPalindromicSubstrings(str2));
44+
for (const { str, expected } of testCases) {
45+
const result = countPalindromicSubstrings(str);
46+
console.log(`Input: "${str}" | Output: ${result} | Expected: ${expected}`);
47+
}
Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,36 @@
11
**Description:**
22
Given a string `str`, return the number of substrings within`str` that are palindromes.
33

4-
**Note:**A palindrome is a string that reads the same backward as forward.
4+
**Note:** A palindrome is a string that reads the same backward as forward.
55

6-
### Examples
7-
Example 1:
8-
Input: str = "abcd"
9-
Output: 4
6+
## Examples
107

11-
Example 2:
12-
Input: str = "aaa"
13-
Output: 3
8+
**Example 1:**
9+
Input: `str = "abcd"`
10+
Output: `4`
11+
Explanation: Each character is a palindrome.
1412

13+
**Example 2:**
14+
Input: `str = "aaa"`
15+
Output: `6`
16+
Explanation: All substrings are palindromes: `"a"`, `"a"`, `"a"`, `"aa"`, `"aa"`, `"aaa"`.
1517

16-
**Algorithmic Steps**
17-
This problem is solved with the help of **Expanding around center** approach. The algorithmic approach can be summarized as follows:
18+
**Example 3:**
19+
Input: `str = "baaab"`
20+
Output: `9`
1821

19-
1. Write a preliminary check by just returning the input string length when its size is less than 2.
22+
## Algorithm
2023

21-
2. Initialize count(`count`) variable to 0, which is used to store the palindromic substrings count.
24+
This problem is efficiently solved using the **expand around center** approach:
2225

23-
3. Iterate over the input string using an iteration variable `i`(from 0 to end of string).
26+
1. If the string is empty, return 0.
27+
2. For each character in the string, treat it as the center of a palindrome and expand outwards to count all odd and even length palindromic substrings.
28+
3. Use a helper function to expand around the center and count palindromes.
29+
4. Sum the counts for all centers and return the total.
2430

25-
4. For each iteration, calculate the total count of odd palindromic substrings using a separate common function(step6). This common function accepts current iteration variable `i` for both left and right pointer values.
2631

27-
5. For each iteration, calculate the total count of even palindromic substrings using a separate common function(step6). This common function accepts current iteration variable `i` as left and `i+1` as right pointer values.
32+
## Complexity
2833

29-
6. The common function is created to iterate over the given string using starting(i.e, `left`) and ending(i.e, `right`) index arguments. The left pointer is going to be decremented and right pointer is going to be incremented whenever the respective character values are equal.
34+
- **Time Complexity:** O(n²)(i.e, O(n²) + O(n²)), where n is the length of the string (for each center, expand up to n). This is because finding both odd and event length palindrome takes `O(n) +O(n)` time complexity and it needs to be repeated on each character position which takes O(n).
3035

31-
7. The sum of even and odd palindromic substring's count is going to be returned as total count for palindromic substrings.
32-
33-
34-
**Time and Space complexity:**
35-
This algorithm has a time complexity of `O(n * 2)`(i.e, `O(n * 2) + O(n * 2)`) because finding both odd and event length palindrome takes `O(n) +O(n)` time complexity and it needs to be repeated on each character position which takes O(n).
36-
37-
Also, it takes space complexity of `O(1)` without using any additional data structure.
36+
- **Space Complexity:** O(1), as no extra data structures are used.
Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
//TC: O(n) SC: O(n)
1+
/**
2+
* TC: O(n) SC: O(n)
3+
* Encodes a list of strings to a single string.
4+
* Uses length-prefix encoding with '#' as a delimiter.
5+
* @param {string[]} strs
6+
* @returns {string}
7+
*/
28
function encodeStrings(strs) {
39
let encodedStr = "";
410
for (let str of strs) {
@@ -7,27 +13,42 @@ function encodeStrings(strs) {
713
return encodedStr;
814
}
915

16+
/**
17+
* Decodes a single string to a list of strings.
18+
* @param {string} str
19+
* @returns {string[]}
20+
*/
1021
function decodeString(str) {
1122
let decodedStrArr = [];
1223
let i = 0;
1324
while (i < str.length) {
1425
let j = i;
15-
while (str[j] != "#") j++;
16-
let start = j+1;
26+
while (str[j] !== "#" && j < str.length) j++;
1727
let wordLength = Number.parseInt(str.substring(i, j));
28+
let start = j + 1;
1829
let subStr = str.substring(start, start + wordLength);
1930
decodedStrArr.push(subStr);
2031
i = start + wordLength;
2132
}
2233
return decodedStrArr;
2334
}
2435

25-
let strs1 = ["learn", "datastructure", "algorithms", "easily"];
26-
let encodedStr1 = encodeStrings(strs1);
27-
console.log(encodedStr1);
28-
console.log(decodeString(encodedStr1));
36+
// Test cases
37+
const testCases = [
38+
["learn", "datastructure", "algorithms", "easily"],
39+
["one", "two", "three"],
40+
["", "a", ""],
41+
["#", "##", "abc#def"],
42+
[],
43+
["", ""],
44+
];
2945

30-
let strs2 = ["one", "two", "three"];
31-
let encodedStr2 = encodeStrings(strs2);
32-
console.log(encodedStr2);
33-
console.log(decodeString(encodedStr2));
46+
for (const arr of testCases) {
47+
const encoded = encodeStrings(arr);
48+
const decoded = decodeString(encoded);
49+
console.log(
50+
`Input: ${JSON.stringify(
51+
arr
52+
)} | Encoded: "${encoded}" | Decoded: ${JSON.stringify(decoded)}`
53+
);
54+
}
Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,39 @@
11
**Description:**
2-
Write an algorithm to encode a list of strings to a single string. After that, the encoded string is decoded back to the original list of strings. Please implement `encode` and `decode`
32

4-
### Examples
5-
Example 1:
6-
Input: ["learn", "datastructure", "algorithms", "easily"]
7-
Output: ["learn", "datastructure", "algorithms", "easily"]
3+
Write an algorithm to encode a list of strings to a single string, and then decode it back to the original list. Implement both `encode` and `decode` functions.
84

9-
Example 2:
10-
Input: ["one", "two", "three"]
11-
Output: ["one", "two", "three"]
5+
#### Examples
126

7+
**Example 1:**
8+
Input: `["learn", "datastructure", "algorithms", "easily"]`
9+
Output: `["learn", "datastructure", "algorithms", "easily"]`
1310

14-
**Algorithmic Steps**
15-
This problem is solved with the help of basic string and array built-in operations. The algorithmic approach can be summarized as follows:
11+
**Example 2:**
12+
Input: `["one", "two", "three"]`
13+
Output: `["one", "two", "three"]`
1614

17-
**Encode string**
18-
1. Initialize an empty string(`encodedStr`) to store the encoded string.
15+
**Example 3:**
16+
Input: `["#", "##", "abc#def"]`
17+
Output: `["#", "##", "abc#def"]`
1918

20-
2. Iterate over the array of strings. For each string iteration, add a prefix with the combination of string length and special(`#`) symbol before each word/string.
19+
## Algorithm
2120

22-
3. Return the encoded string as an output.
21+
### Encode
2322

24-
**Decode string**
23+
1. Initialize an empty string `encodedStr`.
24+
2. For each string in the input array, append its length, a delimiter (e.g., `#`), and the string itself to `encodedStr`.
25+
3. Return the concatenated string.
2526

26-
1. Initialize an empty array(`decodedStrArr`) to store the decoded string.
27+
### Decode
2728

28-
2. Initialize an index variable(`i`) to 0, which is used to iterate over the input string.
29+
1. Initialize an empty array `decodedStrArr` and an index variable `i = 0`.
30+
2. While `i` is less than the length of the encoded string:
31+
- Find the next delimiter (`#`) to determine the length prefix.
32+
- Parse the length, extract the substring of that length, and add it to the result array.
33+
- Move the index past the extracted substring and repeat.
34+
3. Return the array of decoded strings.
2935

30-
3. Iterate over an input string until the end of its length.
36+
## Complexity
3137

32-
4. Create a temporary variable(`j`) which is assigned to index variable.
33-
34-
5. Skip the prefix related to each string's length until the character reaches special(`#`) symbol. The number of characters ignored are indicated by incremental value of `j`. The next character position(`j+1`) indicates the beginning of a string.
35-
36-
6. Calculate the word length followed by substring using the index variables.
37-
38-
7. Add each substring to the decoded string array. Also, increment the index variable to be used for the next substring.
39-
40-
8. Repeat steps 4-7 until all the strings decoded and return the decoded strings.
41-
42-
**Time and Space complexity:**
43-
This algorithm has a time complexity of `O(n)` for both encoding and decoding functions, where `n` is the number of total characters for each string in the input array. This is because we need to iterate over each string in the array to perform constant-time operations for encoding function. In the same way, we need iterate over all the characters of a encoded string for decoding function.
44-
45-
Also, it takes space complexity of `O(n)` to store all the characters.
38+
- **Time Complexity:** O(n) for both encoding and decoding, where n is the total number of characters in all strings.
39+
- **Space Complexity:** O(n), for the encoded string and the decoded array.

0 commit comments

Comments
 (0)