BackmediumStringsUber

Intergalactic Communication Solution

Problem Statement

Given a string S consisting solely of the characters 'x' and 'y', a valid signal is any contiguous substring that (1) contains the same number of 'x' and 'y' characters, and (2) never has two identical characters adjacent to each other. Implement a function that returns the total count of valid signals present in S. The solution must run in linear time relative to |S| and use only O(1) extra memory beyond the input.

Example 1
Input
xyxy
Output
4

Explanation: Substrings of length 2: "xy" (0‑1), "yx" (1‑2) and "xy" (2‑3) are balanced and have no repeats. The length‑4 substring "xyxy" (0‑3) also meets both criteria. No other substrings are balanced. Hence 4 valid signals.

Example 2
Input
xxyy
Output
1

Explanation: Only the substring "xy" (positions 1‑2) has equal numbers of 'x' and 'y' and lacks consecutive repeats. All other substrings either contain "xx"/"yy" or have unequal counts, so the answer is 1.

Example 3
Input
yxyxxy
Output
5

Explanation: The string splits into two alternating parts because of the "xx" at positions 3‑4. In the first part "yxyx" (indices 0‑3) the balanced, non‑repeating substrings are: "yx" (0‑1), "xy" (1‑2), "yx" (2‑3) and "yxyx" (0‑3). In the second part "xy" (indices 4‑5) the substring "xy" is also valid. Total valid signals = 4 + 1 = 5.

Constraints

  • 1 <= S.length <= 100000
  • S[i] is either 'x' or 'y'
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Intergalactic Communication — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(N)
|
SpaceO(1)

Problem Description

Given a string S consisting solely of the characters 'x' and 'y', a *valid signal* is any contiguous substring that (1) contains the same number of 'x' and 'y' characters, and (2) never has two identical characters adjacent to each other. Implement a function that returns the total count of valid signals present in S. The solution must run in linear time relative to |S| and use only O(1) extra memory beyond the input.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Intergalactic Communication"

medium

WHY DOES IT MATTER?

This problem highlights the importance of recognizing structural constraints in string problems. The 'no adjacent identical characters' condition transforms the problem from a general substring counting problem into one that can be solved by analyzing maximal alternating runs. This pattern is common in problems involving sequences with local constraints, and recognizing it allows for significant optimization from O(N^2) to O(N).

OPTIMIZATION CHALLENGE

The key optimization is recognizing that valid substrings must be even-length substrings within maximal alternating runs. Instead of checking every possible substring, we only need to count the number of even-length substrings in each run. This reduces the problem from O(N^2) substring checks to O(N) run identification plus O(1) counting per run.

REAL-WORLD CONNECTION

This pattern is analogous to signal processing in telecommunications, where valid signals must follow specific alternating patterns to avoid interference. For example, in digital communication, alternating bit patterns (like '1010...') are used for clock recovery and synchronization. Counting valid signal segments is similar to identifying valid data frames in a noisy stream, where only segments with specific structural properties are considered valid.

In an interview, start by clarifying the constraints and asking for examples. Then, explain the naive approach and why it's inefficient. Next, introduce the insight about alternating runs and how it simplifies the problem. Finally, present the O(N) solution with clear code and complexity analysis. Emphasize the importance of recognizing structural constraints in string problems.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem requires counting substrings that satisfy two strict conditions: equal counts of 'x' and 'y', and no adjacent identical characters. A naive approach checking every substring would result in O(N^3) or O(N^2) complexity, which is infeasible for large inputs. The key insight is that condition (2) severely restricts the structure of valid substrings. Specifically, any valid substring must be an alternating sequence like 'xyxy...' or 'yxyx...'. This means that if we fix a starting index, the entire substring is determined by its length and the starting character. However, we can further optimize by observing that valid substrings must be part of a maximal alternating run. Within any maximal alternating run of length L, we can count valid substrings in O(1) per run. A valid substring of length 2k (even length) within an alternating run will always have equal 'x' and 'y' counts. Therefore, the problem reduces to finding all maximal alternating runs and counting the number of even-length substrings within each run.

Interview Questions on This Problem

Q1How would you modify your solution if the string could contain more than two characters, but the condition was still 'no adjacent identical characters' and 'equal counts of all characters'?

The approach would need to change significantly. For more than two characters, the 'equal counts' condition becomes harder to satisfy in an alternating pattern. You would likely need a sliding window with a frequency map to track counts, but the 'no adjacent identical' condition still restricts the window to be part of an alternating sequence. However, with more than two characters, an alternating sequence doesn't guarantee equal counts of all characters. You would need to check the frequency map for each potential window, which might lead to O(N^2) or O(N * K) complexity, where K is the number of distinct characters. The O(1) per run optimization would no longer apply directly.

Q2What is the time complexity of your solution, and how do you prove it?

The time complexity is O(N), where N is the length of the string. We traverse the string once to identify maximal alternating runs. For each run of length L, we calculate the number of valid substrings in O(1) using the formula floor(L/2). Since each character is visited exactly once during the run identification phase, the total time is linear. The space complexity is O(1) as we only use a few variables to track the current run length and the total count.

Q3Can you provide an example where a substring has equal 'x' and 'y' counts but is not a valid signal?

Yes. Consider the substring 'xxyy'. It has two 'x's and two 'y's, so the counts are equal. However, it contains adjacent 'x's ('xx') and adjacent 'y's ('yy'), violating the second condition. Another example is 'xyyx', which has two 'x's and two 'y's, but contains adjacent 'y's ('yy'). These substrings would be counted by a naive approach that only checks counts, but they must be excluded by our solution.

Examples

Example 1

Input

xyxy

Output

4

Explanation: Substrings of length 2: "xy" (0‑1), "yx" (1‑2) and "xy" (2‑3) are balanced and have no repeats. The length‑4 substring "xyxy" (0‑3) also meets both criteria. No other substrings are balanced. Hence 4 valid signals.

Example 2

Input

xxyy

Output

1

Explanation: Only the substring "xy" (positions 1‑2) has equal numbers of 'x' and 'y' and lacks consecutive repeats. All other substrings either contain "xx"/"yy" or have unequal counts, so the answer is 1.

Example 3

Input

yxyxxy

Output

5

Explanation: The string splits into two alternating parts because of the "xx" at positions 3‑4. In the first part "yxyx" (indices 0‑3) the balanced, non‑repeating substrings are: "yx" (0‑1), "xy" (1‑2), "yx" (2‑3) and "yxyx" (0‑3). In the second part "xy" (indices 4‑5) the substring "xy" is also valid. Total valid signals = 4 + 1 = 5.

Constraints

  • 1 <= S.length <= 100000
  • S[i] is either 'x' or 'y'

Optimal Approach & Strategy

Traverse the string to identify maximal alternating runs. For each run of length L, add floor(L/2) to the total count, as this represents the number of even-length substrings in the run. This approach runs in O(N) time and O(1) space.

Brute Force Approach

Iterate over all possible substrings using two nested loops. For each substring, check if it has equal 'x' and 'y' counts and no adjacent identical characters. This approach has O(N^3) time complexity due to the substring checks.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function countValidSignals(s) {
    const n = s.length;
    if (n === 0) return 0;
    
    let total = 0;
    let i = 0;
    
    while (i < n) {
        let j = i;
        // Extend the alternating segment as far as possible
        while (j + 1 < n && s[j] !== s[j + 1]) {
            j++;
        }
        const len = j - i + 1;
        const k = Math.floor(len / 2);
        total += k * (k + 1) / 2;
        i = j + 1;
    }
    
    return total;
}

// Driver code
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    terminal: false
});

rl.on('line', (line) => {
    const s = line.trim();
    console.log(countValidSignals(s));
    rl.close();
});

Asked in Top Tech Interviews

Uber

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.