Open In App

Minimum Segments in Seven Segment Display

Last Updated : 26 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

A seven-segment display can be used to display numbers. Given an array of n natural numbers. The task is to find the number in the array that uses the minimum number of segments to display the number. If multiple numbers have a minimum number of segments, output the number having the smallest index.

Seven Segment Display

Examples :  

Input : arr[] = { 1, 2, 3, 4, 5 }.
Output : 1
Explanation: The element that uses the minimum number of segments is 1 ( i.e. 2 segments)

Input : arr[] = { 489, 206, 745, 123, 756 }.
Output : 745
Explanation: The element with smallest index that uses the minimum number of segments is 745 ( i.e. 12 segments)

The idea is to precompute the number of segment used by digits from 0 to 9 and store it. Now for each element of the array sum the number of segment used by each digit. Then find the element which is using the minimum number of segments.

The number of segment used by digit: 
0 -> 6 
1 -> 2 
2 -> 5 
3 -> 5 
4 -> 4 
5 -> 5 
6 -> 6 
7 -> 3 
8 -> 7 
9 -> 6

C++
#include<bits/stdc++.h>
using namespace std;

// Precomputed values of segment used by digit 0 to 9.
const int seg[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6};

// Return the number of segments used by x.
int computeSegment(int x)
{
    if (x == 0)
        return seg[0];

    int count = 0;

    // Finding sum of the segment used by
    // each digit of a number.
    while (x)
    {
        count += seg[x%10];
        x /= 10;
    }

    return count;
}

int elementMinSegment(vector<int> arr, int n)
{
    // Initialising the minimum segment and minimum
    // number index.
    int minseg = computeSegment(arr[0]);
    int minindex = 0;

    // Finding and comparing segment used
    // by each number arr[i].
    for (int i = 1; i < n; i++)
    {
        int temp = computeSegment(arr[i]);

        // If arr[i] used less segment then update
        // minimum segment and minimum number.
        if (temp < minseg)
        {
            minseg   = temp;
            minindex = i;
        }
    }

    return arr[minindex];
}

int main()
{
    vector<int> arr = {489, 206, 745, 123, 756};
    int n = arr.size(); 
    cout << elementMinSegment(arr, n) << endl;
    return 0;
}
Java Python C# JavaScript

Output
745

Time Complexity: O(n * log10n)
Auxiliary Space: O(10)



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg