Skip to content
Discussion options

You must be logged in to vote

We need to count all substrings that contain only '1's in a binary string.

Approach:

The key insight is that for a contiguous group of n '1's:

  • The number of substrings within that group is n*(n+1)/2
  • For example, "111" has 6 substrings: "1", "1", "1", "11", "11", "111"

So we can:

  1. Find all contiguous groups of '1's
  2. For each group of length n, calculate n*(n+1)/2
  3. Sum all these values

Let's implement this solution in PHP: 1513. Number of Substrings With Only 1s

<?php
/**
 * @param String $s
 * @return Integer
 */
function numSub($s) {
    $mod = 1000000007;
    $total = 0;
    $currentCount = 0;

    for ($i = 0; $i < strlen($s); $i++) {
        if ($s[$i] == '1') {
            $currentCount

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Nov 16, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Nov 16, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants