Find fair split of a two-color necklace

Quick Overview

This question evaluates algorithm design and combinatorial reasoning on circular sequences in the coding & algorithms domain, testing string/array manipulation, feasibility-condition analysis (e.g., parity constraints), and the ability to produce linear-time, low-space partitioning algorithms.

Find fair split of a two-color necklace

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

Given a circular necklace represented by a string s over {'a','b'}, you may cut the necklace at most twice (yielding three contiguous pieces). Can you assign these three pieces to two people so that each person receives exactly the same number of 'a' beads and the same number of 'b' beads? If it is possible, return any valid pair of cut indices on the circle and the assignment of pieces to each person; otherwise return 'impossible'. Explicitly state feasibility conditions (e.g., necessary parity constraints) and design an algorithm that runs in O(n) time with O( 1) or O(n) extra space. Analyze correctness and complexity. Follow-up: extend to three gem types (e.g., {'a','b','c'}) where you may make at most three cuts (producing four pieces) and still split between two people so each receives equal counts of every type. Provide the generalized algorithm, state required conditions, and discuss how your approach scales with the number of gem types.

Quick Answer: This question evaluates algorithm design and combinatorial reasoning on circular sequences in the coding & algorithms domain, testing string/array manipulation, feasibility-condition analysis (e.g., parity constraints), and the ability to produce linear-time, low-space partitioning algorithms.

|Home/Coding & Algorithms/Google
Google logo
Google
Sep 6, 2025, 12:00 AM
mediumSoftware EngineerOnsiteCoding & Algorithms
15
0

Given a circular necklace represented by a string s over {'a','b'}, you may cut the necklace at most twice (yielding three contiguous pieces). Can you assign these three pieces to two people so that each person receives exactly the same number of 'a' beads and the same number of 'b' beads? If it is possible, return any valid pair of cut indices on the circle and the assignment of pieces to each person; otherwise return 'impossible'. Explicitly state feasibility conditions (e.g., necessary parity constraints) and design an algorithm that runs in O(n) time with O(

  1. or O(n) extra space. Analyze correctness and complexity. Follow-up: extend to three gem types (e.g., {'a','b','c'}) where you may make at most three cuts (producing four pieces) and still split between two people so each receives equal counts of every type. Provide the generalized algorithm, state required conditions, and discuss how your approach scales with the number of gem types.

Submit Your Answer to Earn 20XP

Sign in to leave a comment

Loading comments...