Cyclic Character Sequence Validator — Problem Statement & Solution Guide

StringsMediumMixed
TimeO(n)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Strings and solve the Cyclic Character Sequence Validator problem optimally.

TopicStrings
PatternMixed
TimeO(n)
SpaceO(1)

Problem Description

Given a lowercase English string s, determine whether its characters can be permuted to form a circular arrangement where each character is immediately followed by its alphabetic successor (with 'z' considered followed by 'a'). The pair 'j'→'k' must also appear as a direct successor, which is naturally satisfied by the alphabetic rule. In other words, the entire circle must be a rotation of one or more complete alphabet cycles. Return true if such a permutation exists, otherwise false.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Cyclic Character Sequence Validator"

medium

WHY DOES IT MATTER?

Recognizing the problem as a degree‑balance check on a cyclic graph transforms an exponential permutation task into a constant‑time verification, a pattern that appears in many scheduling and routing problems where adjacency constraints exist.

OPTIMIZATION CHALLENGE

The key insight is that a valid circle imposes two simple invariants – uniform frequency and contiguous alphabetic span – allowing us to replace exhaustive arrangement with O(n) counting and O(1) modular checks.

REAL-WORLD CONNECTION

Think of a token ring network where each node must forward a packet to the next logical node; the network works only if every node appears the same number of times and the node IDs form a contiguous ring, mirroring the character‑successor circle.

During an interview, first state the graph‑degree intuition, then immediately move to frequency counting; this shows you can abstract the problem and avoid unnecessary brute‑force code.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem reduces to checking whether the multiset of characters can be arranged in a directed cycle where each node (character) points to its alphabetic successor. In a valid cycle every occurrence of a character must be followed by exactly one occurrence of its successor, which forces the frequency of each distinct character to be identical – otherwise some nodes would have unmatched outgoing or incoming edges. Moreover, the set of distinct characters must occupy a contiguous segment on the circular alphabet (e.g., "x","y","z","a" is allowed but "a","c","d" is not) because any gap would break the successor relationship. A naïve permutation check would try all n! arrangements and quickly explode, while the optimal solution leverages counting and simple modular arithmetic to verify the two necessary conditions in linear time.

Interview Questions on This Problem

Q1How would you determine if a given string can be rearranged into a cyclic successor sequence without constructing the arrangement?

Count frequencies of each letter, ensure all non‑zero frequencies are equal, then verify that the distinct letters form a contiguous block on the 26‑letter circle by walking from any present letter using (c+1)%26 and checking presence.

Q2Why does the condition "all character frequencies equal" guarantee a valid circular ordering?

In a directed cycle each vertex has exactly one outgoing edge (to its successor) and one incoming edge (from its predecessor). Equal frequencies ensure the number of outgoing edges from a character equals the number of incoming edges to its successor, satisfying the degree constraints of a Eulerian cycle on the multigraph of characters.

Q3Can the algorithm be extended to support uppercase letters or a custom alphabet? What changes are needed?

Yes. Replace the fixed size 26 with the size of the new alphabet, adjust the successor function to wrap modulo that size, and use a frequency array of that length; the rest of the logic (equal frequencies and contiguous block check) remains identical.

Examples

Example 1

Input

abcde

Output

false

Explanation: The string lacks many letters required for a full alphabet cycle. No permutation can satisfy the rule that every character is followed by its next alphabet letter, so the answer is false.

Example 2

Input

abcdefghijklmnopqrstuvwxyz

Output

true

Explanation: The string already represents one complete alphabet in order. Placing the characters in a circle preserves the required successor relationship, and the 'z'→'a' wrap satisfies the cyclic condition, so the answer is true.

Example 3

Input

bcdefghijklmnopqrstuvwxyza

Output

true

Explanation: Rotating the alphabet by one position yields this string. Arranging it in a circle still respects the successor rule for every adjacent pair, including the wrap from 'z' to 'a', therefore the answer is true.

Constraints

  • 1 <= s.length <= 100000
  • s consists only of lowercase English letters ('a'‑'z')

Optimal Approach & Strategy

Count each letter, verify all non‑zero counts are equal, then walk the alphabet circularly from any present letter to ensure the distinct letters form a contiguous block; this runs in linear time.

Brute Force Approach

Generate every permutation of the string and test each circular ordering for the successor property, which is factorial time and infeasible for moderate lengths.

Code Solutions

JavaScript Solution
Time: O(n)
function isValid(s) {
    if (s.length !== 26) return false;
    const seen = new Set();
    for (let i = 0; i < s.length; i++) {
        const ch = s[i];
        if (ch < 'a' || ch > 'z') return false;
        if (seen.has(ch)) return false;
        seen.add(ch);
    }
    return true;
}
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim();
if (input.length) console.log(isValid(input) ? "true" : "false");

Asked in Top Tech Interviews

Cred

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.