Split a color array into the fewest contiguous single-color subarrays

Quick Overview

Given an array of item colors, find the fewest contiguous pieces it can be split into so that every piece holds a single color. It tests reducing the task to one pass over adjacent elements and arguing why the resulting count cannot be beaten.

Split a color array into the fewest contiguous single-color subarrays

Company: Tencent

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

You are given an integer array `colors` where each element represents the color of an item. Split the array into the minimum number of contiguous subarrays such that within each subarray, all elements have the same color. Return the minimum number of subarrays needed. In other words, count the number of maximal runs of consecutive equal elements in `colors`. ### Function Signature ```python def min_splits(colors: list[int]) -> int: ``` ### Rules - The subarrays partition the array: every element belongs to exactly one subarray, each subarray is a non-empty block of consecutive positions, and the original order is kept. - Equal colors separated by a different color cannot share a subarray. ### Constraints - `1 <= len(colors) <= 10^5` - `1 <= colors[i] <= 10^9` ### Examples ```text Input: colors = [1,1,2,2,3,1,1] Output: 4 ``` The runs are `[1,1]`, `[2,2]`, `[3]` and `[1,1]`. Color 1 appears in two separate runs because the 2s and the 3 sit between them. ```text Input: colors = [5,5,5,5,5] Output: 1 ``` All elements have the same color, so one subarray covers the whole array.

Overview: Given an array of item colors, find the fewest contiguous pieces it can be split into so that every piece holds a single color. It tests reducing the task to one pass over adjacent elements and arguing why the resulting count cannot be beaten.

Tencent logo
Tencent
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

You are given an integer array colors where each element represents the color of an item.

Split the array into the minimum number of contiguous subarrays such that within each subarray, all elements have the same color. Return the minimum number of subarrays needed.

In other words, count the number of maximal runs of consecutive equal elements in colors.

Function Signature

def min_splits(colors: list[int]) -> int:

Rules

  • The subarrays partition the array: every element belongs to exactly one subarray, each subarray is a non-empty block of consecutive positions, and the original order is kept.
  • Equal colors separated by a different color cannot share a subarray.

Constraints

  • 1 <= len(colors) <= 10^5
  • 1 <= colors[i] <= 10^9

Examples

Input: colors = [1,1,2,2,3,1,1]
Output: 4

The runs are [1,1], [2,2], [3] and [1,1]. Color 1 appears in two separate runs because the 2s and the 3 sit between them.

Input: colors = [5,5,5,5,5]
Output: 1

All elements have the same color, so one subarray covers the whole array.