7 Segment Display

Last Updated : 2 Aug, 2026

Given a string s of size n representing an n digit number displayed on a seven segment display, find smallest possible n digit number that uses same number of segments. 

Note: As shown in the below image, the number of segments used by digits 0 to 9 are 6, 2, 5, 5, 4, 5, 6, 7 and 6 respectively.

7SegmentDisplay

Examples:

Input: s = "234567"
Output: 000011
Explanation: The digits in "234567" use a total of 28 segments. The smallest 6-digit number that can be formed using exactly 28 segments is 000011.

Input: s = "9"
Output: 0
Explanation: The digit 9 uses 6 segments. Since 0 also uses 6 segments and is smaller, the answer is 0.

Try It Yourself
redirect icon

[Naive Approach] Using Backtracking - O(10 ^ n) Time and O(n) Space

Starting from the leftmost position, we try placing every digit from 0 to 9 (in increasing order). If a digit can be formed using the remaining segments, we place it and recursively solve the remaining positions. Since we begin trying with 0, we always get the smallest.

  • Count the total number of segments available from all digits in the given string.
  • Create an empty result string of length n.
  • Start filling the result from the leftmost position using recursion.
  • At each position, try every digit from 0 to 9 in increasing order.
  • If the chosen digit can be formed using the remaining segments, place it and recursively fill the next position.
  • If all positions are filled and all segments are used exactly, return the constructed number; otherwise, backtrack and try the next digit.
C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to build the smallest valid number.
bool solve(int pos, int n, int remainingSegments, string &result, vector<int> &seg)
{
    // If all positions are filled, check whether all segments are used.
    if (pos == n)
        return (remainingSegments == 0);

    // Try digits from smallest to largest.
    for (int digit = 0; digit <= 9; digit++)
    {
        // Skip if this digit requires more segments than available.
        if (seg[digit] > remainingSegments)
            continue;

        result[pos] = digit + '0';

        // Recur for the next position.
        if (solve(pos + 1, n, remainingSegments - seg[digit], result, seg))
            return true;

        // Backtracking happens automatically as
        // result[pos] will be overwritten.
    }

    return false;
}

string sevenSegments(string &s)
{
    int n = s.size();

    // Segments used by digits 0 to 9.
    vector<int> seg = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};

    // Count the total number of available segments.
    int totalSegments = 0;
    for (char ch : s)
        totalSegments += seg[ch - '0'];

    string result(n, '0');

    solve(0, n, totalSegments, result, seg);

    return result;
}

int main()
{
    string s = "234567";
    cout << sevenSegments(s) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {

    // Recursive function to build the smallest valid
    // number.
    static boolean solve(int pos, int n,
                         int remainingSegments,
                         char[] result, int[] seg)
    {
        // If all positions are filled, check whether all
        // segments are used.
        if (pos == n)
            return remainingSegments == 0;

        // Try digits from smallest to largest.
        for (int digit = 0; digit <= 9; digit++) {

            // Skip if this digit requires more segments
            // than available.
            if (seg[digit] > remainingSegments)
                continue;

            result[pos] = (char)('0' + digit);

            // Recur for the next position.
            if (solve(pos + 1, n,
                      remainingSegments - seg[digit],
                      result, seg))
                return true;

            // Backtracking happens automatically as
            // result[pos] will be overwritten.
        }

        return false;
    }

    static String sevenSegments(String s)
    {
        int n = s.length();

        // Segments used by digits 0 to 9.
        int[] seg = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };

        // Count the total number of available segments.
        int totalSegments = 0;
        for (char ch : s.toCharArray())
            totalSegments += seg[ch - '0'];

        char[] result = new char[n];

        solve(0, n, totalSegments, result, seg);

        return new String(result);
    }

    public static void main(String[] args)
    {
        String s = "234567";
        System.out.println(sevenSegments(s));
    }
}
Python
# Recursive function to build the smallest valid number.
def solve(pos, n, remaining_segments, result, seg):

    # If all positions are filled, check whether all segments are used.
    if pos == n:
        return remaining_segments == 0

    # Try digits from smallest to largest.
    for digit in range(10):

        # Skip if this digit requires more segments than available.
        if seg[digit] > remaining_segments:
            continue

        result[pos] = str(digit)

        # Recur for the next position.
        if solve(pos + 1, n, remaining_segments - seg[digit], result, seg):
            return True

        # Backtracking happens automatically as
        # result[pos] will be overwritten.

    return False


def sevenSegments(s):
    n = len(s)

    # Segments used by digits 0 to 9.
    seg = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

    # Count the total number of available segments.
    total_segments = 0
    for ch in s:
        total_segments += seg[int(ch)]

    result = ['0'] * n

    solve(0, n, total_segments, result, seg)

    return ''.join(result)

# Driver Code
if __name__ == "__main__":
    s = "234567"
    print(sevenSegments(s))
C#
using System;

class GFG {
    
    // Recursive function to build the smallest valid
    // number.
    static bool Solve(int pos, int n, int remainingSegments,
                      char[] result, int[] seg)
    {
        // If all positions are filled, check whether all
        // segments are used.
        if (pos == n)
            return remainingSegments == 0;

        // Try digits from smallest to largest.
        for (int digit = 0; digit <= 9; digit++) {
            // Skip if this digit requires more segments
            // than available.
            if (seg[digit] > remainingSegments)
                continue;

            result[pos] = (char)('0' + digit);

            // Recur for the next position.
            if (Solve(pos + 1, n,
                      remainingSegments - seg[digit],
                      result, seg))
                return true;

            // Backtracking happens automatically as
            // result[pos] will be overwritten.
        }

        return false;
    }

    static string sevenSegments(string s)
    {
        int n = s.Length;

        // Segments used by digits 0 to 9.
        int[] seg = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };

        // Count the total number of available segments.
        int totalSegments = 0;
        foreach(char ch in s) totalSegments
            += seg[ch - '0'];

        char[] result = new char[n];

        Solve(0, n, totalSegments, result, seg);

        return new string(result);
    }

    static void Main()
    {
        string s = "234567";
        Console.WriteLine(sevenSegments(s));
    }
}
JavaScript
// Recursive function to build the smallest valid number.
function solve(pos, n, remainingSegments, result, seg)
{
    // If all positions are filled, check whether all
    // segments are used.
    if (pos === n)
        return remainingSegments === 0;

    // Try digits from smallest to largest.
    for (let digit = 0; digit <= 9; digit++) {

        // Skip if this digit requires more segments than
        // available.
        if (seg[digit] > remainingSegments)
            continue;

        result[pos] = digit.toString();

        // Recur for the next position.
        if (solve(pos + 1, n,
                  remainingSegments - seg[digit], result,
                  seg))
            return true;

        // Backtracking happens automatically as
        // result[pos] will be overwritten.
    }

    return false;
}

function sevenSegments(s)
{
    const n = s.length;

    // Segments used by digits 0 to 9.
    const seg = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 ];

    // Count the total number of available segments.
    let totalSegments = 0;
    for (const ch of s)
        totalSegments += seg[Number(ch)];

    const result = new Array(n).fill("0");

    solve(0, n, totalSegments, result, seg);

    return result.join("");
}

// Driver Code
const s = "234567";
console.log(sevenSegments(s));

Output
000011

[Expected Approach] Using Greedy Method - O(n) Time and O(1) Space

We can greedily build the answer from left to right by always choosing the smallest possible digit. Before placing a digit, we simply check whether the remaining segments are sufficient to fill the remaining positions, where each position requires between 2 and 7 segments. This allows us to construct the smallest valid number efficiently without exploring unnecessary possibilities.

  • Count the total number of segments available from the given string.
  • Traverse each position from left to right.
  • For the current position, try digits from 0 to 9.
  • Compute the remaining segments after choosing the current digit.
  • If the remaining segments can still fill the remaining positions (between 2 × left and 7 × left), place the digit.
  • Update the remaining segment count and continue to the next position.
  • After filling all positions, return the constructed number.
C++
#include <bits/stdc++.h>
using namespace std;

string sevenSegments(string &s)
{
    int n = s.size();

    // Segments used by digits 0 to 9.
    vector<int> seg = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};

    // Count the total number of available segments.
    int totalSegments = 0;
    for (char ch : s)
        totalSegments += seg[ch - '0'];

    // Stores the smallest possible number.
    string result(n, '0');

    // Fill each position from left to right.
    for (int i = 0; i < n; i++)
    {
        // Number of positions left after the current position.
        int left = n - i - 1;

        // Try digits from smallest to largest.
        for (int digit = 0; digit <= 9; digit++)
        {
            // Remaining segments after placing the current digit.
            int remaining = totalSegments - seg[digit];

            // Place the digit only if the remaining positions can
            // still be filled using the remaining segments.
            if (remaining >= 2 * left && remaining <= 7 * left)
            {
                result[i] = digit + '0';
                totalSegments = remaining;
                break;
            }
        }
    }

    return result;
}

int main()
{
    string s = "234567";
    cout << sevenSegments(s) << endl;
    return 0;
}
Java
import java.util.*;

class GFG {

    static String sevenSegments(String s)
    {
        int n = s.length();

        // Segments used by digits 0 to 9.
        int[] seg = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };

        // Count the total number of available segments.
        int totalSegments = 0;
        for (char ch : s.toCharArray())
            totalSegments += seg[ch - '0'];

        // Stores the smallest possible number.
        char[] result = new char[n];

        // Fill each position from left to right.
        for (int i = 0; i < n; i++) {

            // Number of positions left after the current
            // position.
            int left = n - i - 1;

            // Try digits from smallest to largest.
            for (int digit = 0; digit <= 9; digit++) {

                // Remaining segments after placing the
                // current digit.
                int remaining = totalSegments - seg[digit];

                // Place the digit only if the remaining
                // positions can still be filled using the
                // remaining segments.
                if (remaining >= 2 * left
                    && remaining <= 7 * left) {
                    result[i] = (char)('0' + digit);
                    totalSegments = remaining;
                    break;
                }
            }
        }

        return new String(result);
    }

    public static void main(String[] args)
    {
        String s = "234567";
        System.out.println(sevenSegments(s));
    }
}
Python
def sevenSegments(s):
    n = len(s)

    # Segments used by digits 0 to 9.
    seg = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

    # Count the total number of available segments.
    total_segments = 0
    for ch in s:
        total_segments += seg[int(ch)]

    # Stores the smallest possible number.
    result = ['0'] * n

    # Fill each position from left to right.
    for i in range(n):

        # Number of positions left after the current position.
        left = n - i - 1

        # Try digits from smallest to largest.
        for digit in range(10):

            # Remaining segments after placing the current digit.
            remaining = total_segments - seg[digit]

            # Place the digit only if the remaining positions can
            # still be filled using the remaining segments.
            if 2 * left <= remaining <= 7 * left:
                result[i] = str(digit)
                total_segments = remaining
                break

    return ''.join(result)

# Driver Code
if __name__ == "__main__":
    s = "234567"
    print(sevenSegments(s))
C#
using System;

class GFG {
    static string sevenSegments(string s)
    {
        int n = s.Length;

        // Segments used by digits 0 to 9.
        int[] seg = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };

        // Count the total number of available segments.
        int totalSegments = 0;
        foreach(char ch in s) totalSegments
            += seg[ch - '0'];

        // Stores the smallest possible number.
        char[] result = new char[n];

        // Fill each position from left to right.
        for (int i = 0; i < n; i++) {
            
            // Number of positions left after the current
            // position.
            int left = n - i - 1;

            // Try digits from smallest to largest.
            for (int digit = 0; digit <= 9; digit++) {
                
                // Remaining segments after placing the
                // current digit.
                int remaining = totalSegments - seg[digit];

                // Place the digit only if the remaining
                // positions can still be filled using the
                // remaining segments.
                if (remaining >= 2 * left
                    && remaining <= 7 * left) {
                    result[i] = (char)('0' + digit);
                    totalSegments = remaining;
                    break;
                }
            }
        }

        return new string(result);
    }

    static void Main()
    {
        string s = "234567";
        Console.WriteLine(sevenSegments(s));
    }
}
JavaScript
function sevenSegments(s)
{
    const n = s.length;

    // Segments used by digits 0 to 9.
    const seg = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 ];

    // Count the total number of available segments.
    let totalSegments = 0;
    for (const ch of s)
        totalSegments += seg[Number(ch)];

    // Stores the smallest possible number.
    const result = new Array(n).fill("0");

    // Fill each position from left to right.
    for (let i = 0; i < n; i++) {

        // Number of positions left after the current
        // position.
        const left = n - i - 1;

        // Try digits from smallest to largest.
        for (let digit = 0; digit <= 9; digit++) {

            // Remaining segments after placing the current
            // digit.
            const remaining = totalSegments - seg[digit];

            // Place the digit only if the remaining
            // positions can still be filled using the
            // remaining segments.
            if (remaining >= 2 * left
                && remaining <= 7 * left) {
                result[i] = digit.toString();
                totalSegments = remaining;
                break;
            }
        }
    }

    return result.join("");
}

// Driver Code
const s = "234567";
console.log(sevenSegments(s));

Output
000011
Comment