String with maximum number of unique characters - GeeksforGeeks

07 Mar, 2022
Given a list of strings, find the largest string among all. The largest string is the string with the largest number of unique characters. 
Example: 
Input : "AN KOW", "LO JO", "ZEW DO RO" 
Output : "ZEW DO RO" 
Explanation : 
"ZEW DO RO" has maximum distinct letters.

Input : "ROMEO", "EMINEM", "RADO"
Output : "ROMEO" 
Explanation : In case of tie, we can print
any of the strings.
 
We iterate over the strings and take a boolean array to check the presence of letters. Also, keep track of the maximum unique letters. Return the string with the maximum number of distinct characters. 
C++
Java
Python3
C#
PHP
Javascript
// C++ code to find// the largest string#include <bits/stdc++.h>using namespace std; // Function to find string// with maximum number of// unique characters.void LargestString(string *na){    int N = sizeof(na) /            sizeof(na[0]);    int c[N];     // Index of string with    // maximum unique characters    int m = 1;     // iterate through    // all strings    for (int j = 0; j < N; j++)    {        // array indicating any        // alphabet included or        // not included        bool character[26];         // count number of unique        // alphabets in each string        for (int k = 0; k < na[j].size(); k++)        {            int x = (int)(na[j][k] - 'A');            if (na[j][k] != ' ' &&                character[x] == false)            {                c[j]++;                character[x] = true;            }        }         // keep track of maximum        // number of alphabets        if (c[j] > c[m])            m = j;    }    // print result    cout << na[m] << endl;} // Driver codeint main(){    string na[] = {"BOB", "A AB C JOHNSON",                   "ANJALI","ASKRIT",                   "ARMAN MALLIK"};     LargestString(na);} // This code is contributed by// Manish Shaw(manishshaw1)
// Java code to find the largest stringimport java.lang.*;import java.io.*;import java.util.Arrays; class Geek {     // Function to find string with maximum    // number of unique characters.    public static void LargestString(String na[])    {        int N = na.length;        int c[] = new int[N];         // Index of string with maximum unique        // characters        int m = 0;         // iterate through all strings        for (int j = 0; j < N; j++)        {            // array indicating any alphabet            // included or not included            boolean character[] = new boolean[26];             // count number of unique alphabets in each string            for (int k = 0; k < na[j].length(); k++)            {                int x = na[j].charAt(k) - 'A';                if ((na[j].charAt(k) != ' ') &&                        (character[x] == false))                {                    c[j]++;                    character[x] = true;                }            }             // keep track of maximum number of alphabets            if (c[j] > c[m])                m = j;        }         // print result        System.out.println(na[m]);    }     // Driver code    public static void main(String[] args)    {        String na[] = {"BOB", "A AB C JOHNSON","ANJALI",                       "ASKRIT", "ARMAN MALLIK"};         LargestString(na);    }}
# Python3 code to find the largest string # Function to find string with maximum# number of unique characters.def LargestString(na):    N = len(na)    c = [0] * N         # Index of string with    # maximum unique characters    m = 0         # Iterate through all strings    for j in range(N):                 # Array indicating any alphabet        # included or not included        character = [False] * 26                 # count number of unique        # alphabets in each string        for k in range(len(na[j])):            x = ord(na[j][k]) - ord('A')                         if ((na[j][k] != ' ') and (character[x] == False)):                c[j] += 1                character[x] = True                         # keep track of maximum            # number of alphabets            if (c[j] > c[m]):                m = j                     # print result    print(na[m]) # Driver codena = ["BOB", "A AB C JOHNSON","ANJALI",                "ASKRIT", "ARMAN MALLIK"]LargestString(na) # This article is Contributed by Sharad Bhardwaj.
// C# code to find the largest stringusing System; class GFG {     // Function to find string with maximum    // number of unique characters.    public static void LargestString(string []na)    {        int N = na.Length;        int []c = new int[N];         // Index of string with maximum unique        // characters        int m = 0;         // iterate through all strings        for (int j = 0; j < N; j++)        {            // array indicating any alphabet            // included or not included            bool []character = new bool[26];             // count number of unique alphabets            // in each string            for (int k = 0; k < na[j].Length; k++)            {                int x = na[j][k] - 'A';                                 if ((na[j][k] != ' ') &&                        (character[x] == false))                {                    c[j]++;                    character[x] = true;                }            }             // keep track of maximum number of            // alphabets            if (c[j] > c[m])                m = j;        }         // print result        Console.Write(na[m]);    }     // Driver code    public static void Main()    {        string []na = {"BOB", "A AB C JOHNSON",           "ANJALI", "ASKRIT", "ARMAN MALLIK"};         LargestString(na);    }} // This code is contributed by nitin mittal.
<?php// PHP implementation to// find the largest string // Function to find string with maximum// number of unique charactersfunction LargestString($na){    $N = sizeof($na);    $c = array_fill(0, $N, 0);         // Index of string with maximum unique    // characters    $m = 0;     // iterate through all strings    for ($j = 0; $j < $N; $j++)    {        // array indicating any alphabet        // included or not included        $character = array_fill(0, 26,                                false);                 // count number of unique        // alphabets in each string        for ($k = 0; $k < strlen($na[$j]);                                    $k++)        {            $x = ord($na[$j][$k]) - 65;            if (($na[$j][$k] != ' ') &&                ($character[$x] == false))            {                $c[$j]++;                $character[$x] = true;            }        }         // keep track of maximum        // number of alphabets        if ($c[$j] > $c[$m])            $m = $j;    }     // print result    echo $na[$m]."\n";} // Driver code$na = array("BOB", "A AB C JOHNSON",            "ASKRIT", "ARMAN MALLIK",                           "ANJALI");LargestString($na); // This code is contributed by mits?>
<script> // C# code to find the largest string  // Function to find string with maximum// number of unique characters.function LargestString(na){    let N = na.length;    let c = new Array(N);     // Index of string with maximum unique    // characters    let m = 1;     // iterate through all strings    for (let j = 0; j < N; j++)    {        // array indicating any alphabet        // included or not included        let character = new Array(26,0);         // count number of unique alphabets        // in each string        for (let k = 0; k < na[j].length; k++)        {            let x = na[j][k].charCodeAt(0)-65;                         if ((na[j][k] != ' ') &&                    (character[x] == 0))            {                c[j]++;                character[x] = 1;            }        }         // keep track of maximum number of        // alphabets        if (c[j] > c[m])            m = j;    }     // print result    document.write(na[m]);} // Driver code let na =["BOB", "A AB C JOHNSON","ANJALI", "ASKRIT", "ARMAN MALLIK"]; LargestString(na);  </script>
Output: 
A AB C JOHNSON
YouTubeGeeksforGeeks507K subscribersString with maximum number of unique characters | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=kjSuTowqkzI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Mithun Kumar
nitin mittal
manishshaw1
mohit kumar 29
arorakashish0911
frequency-counting
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack