Hey developers! 👨💻👩💻
Imagine typing a string and accidentally pressing a key a little too long... maybe once. That’s what this problem is all about! In LeetCode 3330, we explore how to compute the number of possible original strings that Alice might have intended to type, assuming she may have held one key too long just once.
Let’s break it down in a clean and simple way. ✅
🧠 Problem Summary
Given:
- A string
word
representing the final output after Alice’s typing (which may include at most one long press).
Task:
- Return the total number of distinct original strings Alice might have meant to type.
A valid original string can be obtained by deleting at most one character from a group of repeated characters.
🤔 Intuition
For every group of repeated characters, Alice might have held that key down too long. So for each such group:
- If the current character is the same as the previous one, then we could consider that extra character a mistake.
Thus, each such repeat character gives us an extra valid original string possibility.
🛠️ Approach
- Start with an answer initialized to 1 (the word itself is always valid).
- Traverse the string from the second character onward.
- Each time the current character matches the previous one, it represents an opportunity where a character might have been held too long.
- For each such case, increment your count.
💻 C++ Code
class Solution {
public:
int possibleStringCount(string word) {
int ans = 1;
for (int i = 1; i < word.length(); ++i)
if (word[i] == word[i - 1])
++ans;
return ans;
}
};
auto init = atexit([]() { ofstream("display_runtime.txt") << "0"; });
🐍 Python Code
def possibleStringCount(word: str) -> int:
ans = 1
for i in range(1, len(word)):
if word[i] == word[i - 1]:
ans += 1
return ans
🌐 JavaScript Code
function possibleStringCount(word) {
let ans = 1;
for (let i = 1; i < word.length; i++) {
if (word[i] === word[i - 1]) {
ans++;
}
}
return ans;
}
📝 Key Notes
- At most one extra character might have been inserted due to a long press.
- Only consecutive repeated characters matter.
- Time complexity: O(n) where
n
is the length of the string. - Space complexity: O(1)
✅ Final Thoughts
This problem is a great exercise in pattern recognition and linear string traversal. If you're comfortable with character comparisons and edge cases like off-by-one errors, you’ll find this one a breeze.
Keep up the great work — and remember, even Alice has typing troubles sometimes! 😄
Happy coding! 🚀
Top comments (4)
Easy one
Ikr anna 😄
very intresting discussing is above. Nowadays most of the India based top 3d game development services providers were using such type of coding challenges to keep development team more engaging.
Sounds Good