Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print all Substrings of length n possible from the given String
Next article icon

Print all strings of maximum length from an array of strings

Last Updated : 22 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of strings arr[], the task is to print all the strings of maximum length from the given array.

Example:

Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}
Output: aba vcd aba
Explanation:
Maximum length among all the strings from the given array is 3.
The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”.

Input: arr[] = {“abb”, “abcd”, “guw”, “v”}
Output: abcd
Explanation:
Maximum length among all the strings from the given array is 4.
The string having length equal to 4 from the array is “abcd”.

Approach: Follow the steps below to solve the problem:

  1. Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len.
  2. Now, traverse the array of string again and print those strings from the array having a length equal to len.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length
// of the longest string from
// the given array of strings
int maxLength(vector<string> arr)
{
    int len = INT_MIN;
    int N = arr.size();
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores the length
        // of current string
        int l = arr[i].size();
 
        // Update maximum length
        if (len < l) {
 
            len = l;
        }
    }
 
    // Return the maximum length
    return len;
}
 
// Function to print the
// longest strings from the array
void maxStrings(vector<string> arr, int len)
{
    int N = arr.size();
    vector<string> ans;
 
    // Find the strings having length
    // equals to len
    for (int i = 0; i < N; i++) {
        if (len == arr[i].size()) {
            ans.push_back(arr[i]);
        }
    }
 
    // Print the resultant
    // vector of strings
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
}
 
// Function to print all the
// longest strings from the array
void printStrings(vector<string>& arr)
{
    // Find the length of longest string
    int max = maxLength(arr);
 
    // Find and print all the strings
    // having length equals to max
    maxStrings(arr, max);
}
 
// Driver Code
int main()
{
    vector<string> arr
        = { "aba", "aa", "ad", "vcd", "aba" };
    printStrings(arr);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to find the length
// of the longest String from
// the given array of Strings
static int maxLength(String []arr)
{
    int len = Integer.MIN_VALUE;
    int N = arr.length;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Stores the length
        // of current String
        int l = arr[i].length();
 
        // Update maximum length
        if (len < l)
        {
            len = l;
        }
    }
 
    // Return the maximum length
    return len;
}
 
// Function to print the
// longest Strings from the array
static void maxStrings(String []arr, int len)
{
    int N = arr.length;
    Vector<String> ans = new Vector<String>();
 
    // Find the Strings having length
    // equals to len
    for(int i = 0; i < N; i++)
    {
        if (len == arr[i].length())
        {
            ans.add(arr[i]);
        }
    }
 
    // Print the resultant
    // vector of Strings
    for(int i = 0; i < ans.size(); i++)
    {
        System.out.print(ans.get(i) + " ");
    }
}
 
// Function to print all the
// longest Strings from the array
static void printStrings(String [] arr)
{
     
    // Find the length of longest String
    int max = maxLength(arr);
 
    // Find and print all the Strings
    // having length equals to max
    maxStrings(arr, max);
}
 
// Driver Code
public static void main(String[] args)
{
    String []arr = { "aba", "aa", "ad",
                     "vcd", "aba" };
                      
    printStrings(arr);
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program to implement
# the above approach
import sys
 
# Function to find the length
# of the longest string from
# the given array of strings
def maxLength(arr):
 
    lenn = -sys.maxsize - 1
    N = len(arr)
 
    # Traverse the array
    for i in range(N):
 
        # Stores the length
        # of current string
        l = len(arr[i])
 
        # Update maximum length
        if (lenn < l):
            lenn = l
 
    # Return the maximum length
    return lenn
 
# Function to print the
# longest strings from the array
def maxStrings(arr, lenn):
 
    N = len(arr)
    ans = []
     
    # Find the strings having length
    # equals to lenn
    for i in range(N):
        if (lenn == len(arr[i])):
            ans.append(arr[i])
 
    # Print the resultant
    # vector of strings
    for i in range(len(ans)):
        print(ans[i], end = " ")
 
# Function to print all the
# longest strings from the array
def printStrings(arr):
 
    # Find the length of longest string
    max = maxLength(arr)
 
    # Find and print all the strings
    # having length equals to max
    maxStrings(arr, max)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "aba", "aa", "ad",
            "vcd", "aba" ]
     
    printStrings(arr)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the length
// of the longest String from
// the given array of Strings
static int maxLength(String []arr)
{
    int len = int.MinValue;
    int N = arr.Length;
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {       
        // Stores the length
        // of current String
        int l = arr[i].Length;
 
        // Update maximum length
        if (len < l)
        {
            len = l;
        }
    }
 
    // Return the maximum length
    return len;
}
 
// Function to print the
// longest Strings from the array
static void maxStrings(String []arr,
                       int len)
{
    int N = arr.Length;
    List<String> ans = new List<String>();
 
    // Find the Strings having length
    // equals to len
    for(int i = 0; i < N; i++)
    {
        if (len == arr[i].Length)
        {
            ans.Add(arr[i]);
        }
    }
 
    // Print the resultant
    // vector of Strings
    for(int i = 0; i < ans.Count; i++)
    {
        Console.Write(ans[i] + " ");
    }
}
 
// Function to print all the
// longest Strings from the array
static void printStrings(String [] arr)
{   
    // Find the length of longest String
    int max = maxLength(arr);
 
    // Find and print all the Strings
    // having length equals to max
    maxStrings(arr, max);
}
 
// Driver Code
public static void Main(String[] args)
{
    String []arr = {"aba", "aa", "ad",
                    "vcd", "aba"};                    
    printStrings(arr);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
// Javascript program to implement
// the above approach
 
// Function to find the length
// of the longest String from
// the given array of Strings
function  maxLength(arr)
{
    let len = Number.MIN_VALUE;
    let N = arr.length;
  
    // Traverse the array
    for(let i = 0; i < N; i++)
    {
          
        // Stores the length
        // of current String
        let l = arr[i].length;
  
        // Update maximum length
        if (len < l)
        {
            len = l;
        }
    }
  
    // Return the maximum length
    return len;
}
 
// Function to print the
// longest Strings from the array
function maxStrings(arr,len)
{
    let N = arr.length;
    let ans = [];
  
    // Find the Strings having length
    // equals to len
    for(let i = 0; i < N; i++)
    {
        if (len == arr[i].length)
        {
            ans.push(arr[i]);
        }
    }
  
    // Print the resultant
    // vector of Strings
    for(let i = 0; i < ans.length; i++)
    {
        document.write(ans[i] + " ");
    }
}
 
// Function to print all the
// longest Strings from the array
function printStrings(arr)
{
    // Find the length of longest String
    let max = maxLength(arr);
  
    // Find and print all the Strings
    // having length equals to max
    maxStrings(arr, max);
}
 
// Driver Code
let arr=["aba", "aa", "ad",
                     "vcd", "aba" ];
printStrings(arr);
 
 
 
// This code is contributed by unknown2108
</script>
 
 
Output: 
aba vcd aba

Time Complexity: O(N)
Auxiliary Space: O(N)



Next Article
Print all Substrings of length n possible from the given String

S

svrrrsvr
Improve
Article Tags :
  • Arrays
  • C/C++ Puzzles
  • DSA
  • School Programming
  • Searching
  • Strings
Practice Tags :
  • Arrays
  • Searching
  • Strings

Similar Reads

  • Sort an array of strings according to string lengths
    We are given an array of strings, we need to sort the array in increasing order of string lengths.Examples: Input : {"GeeksforGeeeks", "I", "from", "am"}Output : I am from GeeksforGeeks Input : {"You", "are", "beautiful", "looking"}Output : You are looking beautiful A simple solution is to write our
    10 min read
  • Print all Substrings of length n possible from the given String
    Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = “geeksforgeeks”, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are “gee”, “eek”, “eks”, “ksf”, “sfo”, “for”, “org”, “rge
    8 min read
  • Maximize length of the String by concatenating characters from an Array of Strings
    Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
    12 min read
  • Maximum sum of lengths of a pair of strings with no common characters from a given array
    Given an array arr[] consisting of N strings, the task is to find the maximum sum of length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contains no common characters. Examples: Input: arr[] = ["abcd", "cat", "lto", "car", "wxyz", "abcdef"]Output:
    7 min read
  • Count of Superstrings in a given array of strings
    Given 2 array of strings X and Y, the task is to find the number of superstrings in X. A string s is said to be a Superstring, if each string present in array Y is a subsequence of string s . Examples: Input: X = {"ceo", "alco", "caaeio", "ceai"}, Y = {"ec", "oc", "ceo"}Output: 2Explanation: Strings
    8 min read
  • Longest Common Substring in an Array of Strings
    We are given a list of words sharing a common stem i.e the words originate from same word for ex: the words sadness, sadly and sad all originate from the stem 'sad'. Our task is to find and return the Longest Common Substring also known as stem of those words. In case there are ties, we choose the s
    7 min read
  • Pair of strings having longest common prefix of maximum length in given array
    Given an array of strings arr[], the task is to find the pair of strings from the given array whose length of the longest common prefix between them is maximum. If multiple solutions exist, then print any one of them. Examples: Input: arr[] = {"geeksforgeeks", "geeks", "geeksforcse", } Output: (geek
    15+ min read
  • All possible strings of any length that can be formed from a given string
    Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
    10 min read
  • Find the first maximum length even word from a string
    Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: Input: "this is a test string"Output: stringEven length words
    10 min read
  • Maximum common prefix of all strings
    Given array A[] of strings of size N, the task for this problem is to print the Maximum Common prefix of string 'i' with other strings from 1 to N apart from 'i' itself for all given strings from 1 to N. Given strings consists of lowercase English letters. Examples: Input: {"abc", "abb", "aac"}Outpu
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences