We are given a string s. We need to find the longest substring with alternating characters. The substring must be contiguous and consist of alternating characters, meaning that no two adjacent characters are the same. For example, "ababab" is alternating, "aba" is alternating, "a" is alternating (trivially). We need to return the longest such substring (or its length? The problem says "find the longest substring", so likely return the substring itself. But sometimes they ask for length. Let's read careful: "You are given a string s. Write a function to find the longest substring with alternating characters (e.g., "ababab"). Please write a function that solves this problem, and explain your algorithm." So function should return the substring. However, it's ambiguous. Possibly return length as well. But typical LeetCode style: return the length of the longest alternating substring? Actually there is a known problem: "Longest Substring with Alternating Characters" sometimes asks for length. But the phrasing "find the longest substring" suggests to return the substring. However, the example "ababab" is alternating; but we need to output that substring if it's the longest. But often they ask for the length because returning substring is trivial once we know start and length. But the instruction: "Write a function to find the longest substring" could mean return the substring. We'll decide to return the substring. If multiple have same max length, we can return any (maybe first occurrence). Let's implement function longestAlternatingSubstring(s) returning string.
Algorithm: We can scan the string while maintaining current alternating substring. We'll keep start index of current alternating segment. For each i from 1 to n-1, check if s[i] != s[i-1]; if true, then the alternating condition holds for the pair. If false, then the current alternating segment ends at i-1. Then we start a new segment from i (or i-1? Actually we want the longest contiguous substring where every adjacent pair alternates. When we encounter s[i] == s[i-1], the alternating condition breaks. So the segment from current_start to i-1 is alternating. Then we start a new segment at i-1? Let's think: If s[i] == s[i-1], then any substring that includes both i-1 and i is invalid because adjacent equal. So the next possible alternating segment could start at i (single character) because a single character is alternating. But also consider that if we start at i, then we have a segment of length 1. However, maybe we can start at i-1? But if we start at i-1 and then include i, it's invalid. So the new segment must start at i, because we cannot include both i-1 and i. But note: the segment that ended at i-1 is from start to i-1. The next segment can start at i, but also if we start at i-1 and go forward? Actually we cannot include i-1 and i together, but we could start a new segment that includes i-1 and beyond? No, because if we include i-1 and i, it's invalid. So we must start a new segment at i. However, what about a segment that starts at i-1 and then goes to i+something? That would include the pair (i-1,i) which is equal, so invalid. So indeed we start at i.
But careful: When we find s[i] == s[i-1], the previous alternating substring is from current_start to i-1. Then we set current_start = i (new segment starts at i). Also we need to record the maximum length found.
But what about the case where the alternating condition holds for all characters? Then after loop we need to check the last segment.
Implementation details:
- Initialize start = 0, max_len = 1, max_start = 0.
- For i from 1 to len(s)-1:
if s[i] != s[i-1]:
// continue current alternating substring
// nothing to update except maybe update max at each step? We can compute length as i - start + 1.
// But we only update max when we reach end? Could update after each iteration: current_len = i - start + 1, if current_len > max_len, update.
else:
// break; current segment ends at i-1. Update max if needed for current segment? But we have been updating continuously, so max already captured. But to be safe, after break we can compute current segment length (i - start) and update max if longer. Then set start = i.
- After loop, check the last segment: current_len = n - start, update if needed.
But careful: At each iteration, if condition holds, we can compute length. But we may compute same length multiple times; it's fine.
Alternative: We can simply track current length. Initialize cur_len = 1. For i from 1..n-1:
if s[i] != s[i-1]:
cur_len += 1
else:
cur_len = 1 // start new segment with current character alone? Actually when s[i] == s[i-1], the alternating segment that includes s[i-1] ends. The new segment could start at i (so length 1 includes only s[i]). So set cur_len = 1.
Then after each step, if cur_len > max_len, update max_len and note start? But we also need start index. So we need to track start of current segment. We can do: start variable that moves when we reset. For each i, if s[i] != s[i-1], we keep same start. If s[i] == s[i-1], then we set start = i and cur_len = 1. But careful: When we reset cur_len to 1, start should be i. Also when we continue, start remains unchanged.
So algorithm:
n = len(s)
if n == 0: return ""
max_len = 1
max_start = 0
cur_start = 0
cur_len = 1
for i in range(1, n):
if s[i] != s[i-1]:
cur_len += 1
else:
// reset
cur_start = i
cur_len = 1
if cur_len > max_len:
max_len = cur_len
max_start = cur_start
return s[max_start:max_start+max_len]
But there is a subtlety: When s[i] == s[i-1], we reset cur_len to 1 and cur_start to i. That is correct: the new alternating segment starts at i (a single character). But what about the segment that contains only s[i]? That's fine. Also we update max after resetting? We update max after each iteration; so if cur_len becomes 1 and maybe that's not > max_len, it's fine.
But consider: If we have a segment that ends at i-1 and we reset at i, we lose the segment that ended at i-1. But we have already captured its length in max if it was the longest? Actually we update max in every iteration, so before resetting at i, we would have updated max for the previous iteration's cur_len? Let's step through: suppose at i-1 we had cur_len = L (which includes up to i-1). Then at i, we check condition: if s[i] == s[i-1] then we reset. But before resetting, we should have already updated max at the end of previous iteration (i-1). At i, we reset cur_len=1 and cur_start=i. Then we check if cur_len>max_len: unlikely because 1 is small. So max remains the max from previous. So it's fine. But what about the case where the longest segment ends at i-1 exactly, and we reset at i? That segment's length was captured in max at iteration i-1. So we are good.
But what about the scenario where the condition holds for all characters? Then we never reset, cur_len increments, and we update max each iteration. At the end, max contains the full length.
Edge cases: empty string, single char, all same char, etc.
Complexity: O(n) time, O(1) space.
But we must be careful: The alternating condition requires that every pair of consecutive characters are different. So our algorithm correctly enforces that by checking s[i]!=s[i-1] and resetting when equal.
Now, is there any nuance? The problem says "alternating characters" but the example "ababab" suggests alternating between two different characters? Or does it mean any pattern like a, b, a, b? But what about a longer pattern like "abcabc"? That is not alternating between two characters; it's a repeating pattern of three. But the typical definition of "alternating characters" in such problems means "no two adjacent characters are the same". So "abcabc" is also alternating? Actually "abcabc": a-b (different), b-c (different), c-a (different), a-b (different), b-c (different). So all adjacent pairs are different. So it qualifies. However, sometimes the term "alternating characters" might be interpreted as alternating between two specific characters (like 'a' and 'b' only). But the example "ababab" uses only two characters. But the problem statement says "alternating characters (e.g., "ababab")". It doesn't explicitly say only two characters. So I think it's general: no two adjacent same. Indeed, "alternating" often means switching between different values, but not necessarily only two. However, the typical "longest alternating substring" problem on LeetCode is "Longest Substring with Alternating Characters" where you need to find longest contiguous substring where no two adjacent characters are the same. So that's it.
But also note: The substring must be contiguous. Our algorithm finds contiguous segments.
Potential alternative: There might be a more efficient approach? O(n) is optimal.
Now, let's implement in Python. We'll define function longest_alternating_substring(s: str) -> str.
Testing:
- "ababab" -> should return "ababab"
- "a" -> "a"
- "aa" -> "a" (or "a"? longest substring with alternating chars: cannot have "aa", so either of the single 'a's. Return first? According to algorithm, start=0, cur_len=1; i=1: s[1]==s[0] so reset cur_start=1, cur_len=1; max_len remains 1, max_start=0 (since first update at i=0? Actually we initialize max_len=1, max_start=0. At i=0 we don't iterate. At i=1, after reset cur_len=1 but max_len stays 1; max_start remains 0. So return s[0:1]="a". That's fine.
- "abcabc" -> "abcabc" because all adjacent different.
- "abba" -> Let's see: s="abba": indices: 0:a,1:b,2:b,3:a. Start at 0. i=1: 'b' != 'a' -> cur_len=2; max_len=2, max_start=0. i=2: 'b' == 'b'? s[2]==s[1] both 'b', so reset: cur_start=2, cur_len=1. i=3: s[3]='a' != s[2]='b' -> cur_len=2. Compare: cur_len=2 equals max_len=2, but not >, so max_start stays 0 (first found). So return "ab". But "bba"? Actually "ba"? The segment from index2-3: "ba" is alternating, length2. So both "ab" and "ba" length2. Return first one "ab". That's okay.
- "aab" -> i=1: 'a'=='a', reset, cur_start=1,cur_len=1. i=2: 'b' != 'a', cur_len=2; max_len becomes 2, max_start=1? Actually at i=2, after increment cur_len=2, check > max_len: currently max_len=1 (initialized to 1). Actually at start max_len=1. At i=1 after reset, cur_len=1, no update. At i=2, cur_len=2 > 1, update max_len=2, max_start=cur_start which is 1. So return s[1:3]="ab". That's correct; "ab" is longest alternating substring (length2). Also "aa" is not alternating.
So algorithm seems correct.
But note: We initialize max_len and max_start to 1 and 0 if s non-empty. But we need to handle empty string: return empty string.
Edge case: all characters alternating, e.g., "abcd". The algorithm will give full length.
Now, time complexity O(n), space O(1) extra.
Potential improvements: We could also simply compute lengths and return slice.
Let's write code accordingly.
But we also need to explain algorithm in words. So after writing function, we include explanation.
Let's also consider if substring must be composed of exactly two alternating characters? For example, "abc" has a,b,c all different adjacent, so alternating. That seems fine. But maybe they intended alternating between two specific characters? The phrase "alternating characters" could be ambiguous. However, typical coding problem "Longest Substring with Alternating Characters" (like on LeetCode) asks for a substring where no two adjacent characters are the same. So I'll go with that.
But just to be thorough: If the problem expects only two distinct characters alternating (like pattern ABAB...), then our algorithm might incorrectly accept "abcabc" as valid. However, the problem statement didn't specify "two", it just gave example "ababab". Also the phrase "alternating characters" often means switching between two values, but could be more. Let's check typical definitions: "alternating" in string context: a string is called alternating if it has no two consecutive characters that are the same. That's common. For example, Hackerrank "Alternating Characters" problem counts deletions to make string alternating (no two same adjacent). So that's exactly it.
Thus we'll proceed.
We'll implement function:
def longest_alternating_substring(s: str) -> str:
if not s:
return ""
n = len(s)
max_len = 1
max_start = 0
cur_start = 0
cur_len = 1
for i in range(1, n):
if s[i] != s[i-1]:
cur_len += 1
else:
cur_start = i
cur_len = 1
if cur_len > max_len:
max_len = cur_len
max_start = cur_start
return s[max_start:max_start+max_len]
But check: At reset, cur_start = i. That means new segment starts at i. That segment includes character at i. So length 1. Good.
Now test with a longer example: "abcde" should return entire string.
But let's test: s="abcde":
i=1: b!=a -> cur_len=2, max_len=2, max_start=0.
i=2: c!=b -> cur_len=3, max_len=3, max_start=0.
i=3: d!=c -> cur_len=4, max_len=4, max_start=0.
i=4: e!=d -> cur_len=5, max_len=5, max_start=0. Return full.
Now test with "aabbaa":
Indices: 0:a,1:a,2:b,3:b,4:a,5:a.
Initialize: cur_start=0, cur_len=1, max_len=1, max_start=0.
i=1: a==a? Actually s[1]=='a', s[0]=='a', equal -> reset: cur_start=1, cur_len=1. max_len still 1.
i=2: b!=a? s[2]='b', s[1]='a', not equal -> cur_len=2, cur_start=1. Now cur_len=2 > max_len=1 -> update max_len=2, max_start=1. (substring s[1:3]="ab")
i=3: s[3]='b', s[2]='b' equal -> reset: cur_start=3, cur_len=1.
i=4: s[4]='a' != s[3]='b' -> cur_len=2, cur_start=3. cur_len=2 equals max_len? Actually max_len=2, not >, so no update. So max remains at index1 length2 "ab". i=5: s[5]='a' == s[4]='a' -> reset cur_start=5, cur_len=1. End. So longest substring "ab" (or maybe "ba"? we got "ab"). That is correct because "ab" or "ba" length2. So fine.
But what about substring "aba"? That's alternating and length3. In "aabbaa", we don't have "aba". Actually we have "ab" and "ba". So okay.
Now, is there a case where we might miss a longer substring that starts not at a reset point? Our algorithm essentially finds maximal alternating segments. Because whenever there is an equal pair, it breaks the segment. So each maximal segment is contiguous where all adjacent pairs are different. So we will find them all.
Now, we need to produce the answer: The function and explanation.
We should also discuss time and space complexity.
Potential edge: If the string is all alternating, our algorithm returns the whole string.
Thus final answer.
But note: The problem says "find the longest substring with alternating characters". Could they mean the substring that alternates between exactly two distinct characters? For example, "ababab" uses only 'a' and 'b'. But "abcabc" uses three distinct characters, but still alternates (no two same adjacent). However, sometimes "alternating" might imply that the characters switch back and forth between two values, i.e., pattern ABAB... That would require that the substring's characters at even positions are the same and at odd positions are the same, and the two are different. But that would exclude "abcabc" because even positions: a,c,b? Actually positions 0,2,4: a,c,b - not same. So that's not alternating between two characters. The problem statement does not explicitly say "two", but the example uses two. However, many problems define "alternating characters" as no two adjacent same. I'll check typical problems: LeetCode 2276? Actually there is "Count Integers with Even Digit Sum" no. But there is "Longest Substring with Alternating Characters" - I recall a problem on LeetCode maybe not exactly. There's a problem "Longest Substring with Alternating Characters" on LintCode? Possibly it's "Longest Substring Without Repeating Characters" is different. But I've seen a problem: "Given a string s, find the length of the longest substring where no two adjacent characters are the same." That is sometimes asked. So I'm leaning towards that interpretation.
But to be safe, we could design a solution that checks both? Maybe we should clarify: In the explanation, we can define alternating as "no two consecutive characters are identical". That covers the common definition.
Given that it says "e.g., 'ababab'", they gave an example with two characters, but that's also valid under our definition. They didn't give "abcabc". So it's ambiguous but likely our definition.
I'll produce solution accordingly.
Now, we also might want to return the length instead? The problem: "find the longest substring". Usually you'd return the substring. But sometimes they ask for the length. Could return either. However, if they want the substring, we can return it. If they wanted length, they'd ask "find the length of the longest substring". So I'll return the substring.
But to be safe, we could return both? We'll stick to substring.
We'll write a function in Python:
def longest_alternating(s):
# code
We'll include docstring.
Now, explanation: We'll describe scanning and tracking current alternating segment, resetting when two same adjacent characters encountered, and tracking maximum.
Let's produce final answer with code and explanation.
But before final, let's think if any tricky cases: empty string, single char, all same, etc.
Now, we should also consider that the substring must be contiguous. Our algorithm ensures that.
Complexity: O(n) time, O(1) space.
Now, what about Unicode? We treat characters as Python strings, works.
Thus final answer.
Now produce in required format: first code, then explanation.
But note: The user says: "Please write a function that solves this problem, and explain your algorithm." So we need to output both. We'll produce a Python function with comments, then a separate explanation.
We'll also consider that they might want the solution in a specific language? Not specified. We'll use Python, it's common.
Thus final.
Solution (Python)
def longest_alternating_substring(s: str) -> str:
"""
Returns the longest contiguous substring of `s` where no two adjacent characters are equal.
If there are multiple substrings with the same maximum length, the first one encountered is returned.
"""
if not s: # empty string
return ""
n = len(s)
max_len = 1 # length of the best substring found so far
max_start = 0 # starting index of the best substring
cur_start = 0 # start of the current alternating segment
cur_len = 1 # length of the current segment
for i in range(1, n):
if s[i] != s[i-1]: # still alternating
cur_len += 1
else: # break: two equal adjacent characters
cur_start = i # start a new segment at current character
cur_len = 1 # segment length is 1 (the character itself)
# Update the best segment if the current one is longer
if cur_len > max_len:
max_len = cur_len
max_start = cur_start
return s[max_start:max_start + max_len]
Algorithm Explanation
We need the longest contiguous substring where every pair of adjacent characters differs (i.e., no two consecutive characters are the same). This can be solved by a single linear scan:
-
Initialization
- If the string is empty, return an empty string.
- Set
cur_start = 0 and cur_len = 1 to represent the current alternating segment that starts at the first character and initially contains only that character.
- Keep
max_len and max_start to record the longest segment found so far (initially the first character).
-
Scan the string (from the second character onward)
For each index i (1 ≤ i < n):
- Check adjacency: Compare
s[i] with s[i-1].
- If they are different, the alternating property continues, so increase
cur_len by 1.
- If they are equal, the current segment ends at
i-1. Start a new segment at i by setting cur_start = i and cur_len = 1 (the single character at i).
- Update maximum: After processing
i, if cur_len exceeds max_len, update max_len and max_start to the current segment’s length and start.
-
Result
After the loop, the longest alternating substring is the slice s[max_start : max_start + max_len].
Why this works
Any maximal alternating substring must be bounded by either the start of the string or a pair of equal adjacent characters. The algorithm explicitly detects those boundaries (when s[i] == s[i-1]) and restarts a new segment, thereby enumerating all maximal alternating substrings. By keeping the longest one seen, we guarantee the optimal solution.
Complexity Analysis
- Time: O(n) – we examine each character once.
- Space: O(1) – only a few integer variables are used; the output substring is a view of the original string (O(1) extra space in Python, O(k) for the returned string where k ≤ n).