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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to extract characters in given range from a string list
Next article icon

Python Program To Get Minimum Elements For String Construction

Last Updated : 18 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a String, the task is to write a Python program to count the minimum elements required to form a string from list elements.

Input : test_list = [“geek”, “ring”, “sfor”, “ok”, “woke”], tar_str = “working” 
Output : 2 
Explanation : working can be formed using woke and ring.

Input : test_list = [“geek”, “ring”, “sfor”, “ok”, “woke”], tar_str = “workinggeek” 
Output : 3 
Explanation : workinggeek can be formed using woke, geek and ring. 
 

Method : Using issubset() + set() + combinations()

In this, we iterate for a list of strings and form all size combinations, each combination is converted to set and checked to be forming target string using issubset(), if found, the loop is exited and the count is recorded.

Python3




# Python3 code to demonstrate working of
# Minimum elements for String construction
# Using issubset() + set() + combinations()
from itertools import combinations
 
# initializing list
test_list = ["geek", "ring", "sfor", "ok", "woke"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing target string
tar_str = "working"
 
res = -1
set_str = set(tar_str)
done = False
for val in range(0, len(test_list) + 1):
     
    # creating combinations
    for sub in combinations(test_list, val):
         
        # constructing sets of each combinations
        temp_set = set(ele for subl in sub for ele in subl)
         
        # checking if target string has created set as subset
        if set_str.issubset(temp_set):
            res = val
            done = True
            break
    if done:
        break
 
# printing result
print("The Minimum count elements for string : " + str(res))
 
 
Output
The original list is : ['geek', 'ring', 'sfor', 'ok', 'woke'] The Minimum count elements for string : 2

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method : using set intersection.

This method involves converting the target string into a set and then iterating over the list of strings. For each string in the list, convert it into a set and find its intersection with the target set. If the size of the intersection is equal to the size of the current string, it means that all characters of the current string are present in the target string and hence the current string can be used to construct the target string.

Here’s the code for this approach:

Python3




def get_min_elements(test_list, tar_str):
    set_str = set(tar_str)
    count = 0
    for string in test_list:
        set_string = set(string)
        if len(set_str & set_string) == len(string):
            count += 1
            set_str -= set_string
    return count
 
test_list = ["geek", "ring", "sfor", "ok", "woke"]
tar_str = "working"
print(get_min_elements(test_list, tar_str))
 
 
Output
2

Time Complexity: O(n * m) where n is the length of the target string and m is the number of strings in the list.

Auxiliary Space: O(n + m)



Next Article
Python program to extract characters in given range from a string list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Get Nth column elements in Tuple Strings
    Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
    8 min read
  • First N letters String Construction - Python
    The task of constructing a string from the first N letters of a given string in Python involves extracting a specific portion of the string, starting from the beginning and including the first N characters. For example, if we have the string "GeeksForGeeks" and want to extract the first 5 characters
    3 min read
  • Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
    3 min read
  • Python program to Extract Mesh matching Strings
    Given a character mesh, containing missing characters, match the string which matches the mesh. Example: Input : test_list = ["geeks", "best", "peeks"], mesh = "_ee_s" Output : ['geeks', 'peeks'] Explanation : Elements according to mesh are geeks and peeks. Input : test_list = ["geeks", "best", "tes
    5 min read
  • Python program to extract characters in given range from a string list
    Given a Strings List, extract characters in index range spanning entire Strings list. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], strt, end = 14, 20 Output : sbest Explanation : Once concatenated, 14 - 20 range is extracted.Input : test_list = ["geeksforgeeks", "is", "best",
    4 min read
  • Python program to find String in a List
    Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, we’ll explore several methods to find a string in a list, starting from the most e
    3 min read
  • Python program to check if lowercase letters exist in a string
    Checking for the presence of lowercase letters involves scanning the string and verifying if at least one character is a lowercase letter (from 'a' to 'z'). Python provides simple and efficient ways to solve this problem using built-in string methods and constructs like loops and comprehensions. Usi
    2 min read
  • Python3 Program for Minimum move to end operations to make all strings equal
    Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"}Output : 2Explanation: In first string, we removefirst element("m") from first st
    2 min read
  • Python Program To Find Longest Common Prefix Using Sorting
    Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
    2 min read
  • Python3 Program for Minimum rotations required to get the same string
    Given a string, we need to find the minimum number of rotations required to get the same string.Examples: Input : s = "geeks"Output : 5Input : s = "aaaa"Output : 1Method 1: The idea is based on below post.A Program to check if strings are rotations of each other or notStep 1 : Initialize result = 0
    2 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