Skip to main content
Back to problems
Leetcode
Medium
Arrays
Strings
Hash Maps
Count Valid Prefixes

Count how many prefixes satisfy a validity condition as you scan the input from left to right.

Acceptance 0%
Problem Statement

You are given a string or array and a rule that determines whether a prefix is considered valid. Your task is to examine every prefix starting from the first element and count how many of them satisfy the rule.

A prefix is any initial segment of the sequence, including the entire sequence. For each prefix, evaluate the condition based on the elements seen so far, and return the total number of valid prefixes.

Because prefixes are checked incrementally, the intended solution should avoid recomputing the same information from scratch for every prefix.

Input Format

  • A sequence s or nums representing the input.
  • An implied validity rule over each prefix, determined by the problem definition.

Return the number of prefixes that are valid.

Output Format

  • Return a single integer: the count of valid prefixes.

Constraints

  • The input size is typically large enough that an O(n2)O(n^2) approach is undesirable.
  • Use a running summary of the prefix state to evaluate each prefix efficiently.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 3, 4]

Output

2

Explanation

Illustrative example: suppose a prefix is valid when its running sum is even. The prefix sums are 1, 3, 6, 10, so two prefixes are valid.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.