Leetcode 2900. Longest Unequal Adjacent Groups Subsequence I
Given a string s
consisting of lowercase English letters, the task is to find out the length of the longest subsequence where no two adjacent characters are the same. Note that the characters in the subsequence must appear in the same order as in the given string s
.
s
?Let’s proceed with these assumptions for input constraints for now:
s
is (10^5).s
consists only of lowercase English letters.To solve this problem, we can employ a simple greedy approach:
Here is the C++ implementation:
#include <iostream>
#include <string>
// Function to calculate the longest unequal adjacent groups subsequence length
int longestUnequalAdjacentSubsequence(const std::string &s) {
if (s.empty()) return 0;
int maxLength = 1; // Start with the first character, hence length is at least 1
char lastChar = s[0];
for (size_t i = 1; i < s.length(); ++i) {
if (s[i] != lastChar) {
maxLength++;
lastChar = s[i];
}
}
return maxLength;
}
// Main function for testing
int main() {
std::string s;
std::cout << "Enter the string: ";
std::cin >> s;
int result = longestUnequalAdjacentSubsequence(s);
std::cout << "The length of the longest unequal adjacent groups subsequence is: " << result << std::endl;
return 0;
}
The time complexity for this solution is (O(n)), where (n) is the length of the input string s
. This is because we traverse the string once and perform constant time operations for each character.
1
because at a minimum, the subsequence will have at least one character.This approach ensures that we capture the longest subsequence while only making a single pass through the string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?