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 Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Check if characters of a given string can be used to form any N equal strings
Next article icon

Check if a two character string can be made using given words

Last Updated : 20 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times.

Examples: 

Input : str = "ya"         words[] = {"ah", "oy", "to", "ha"}  Output : YES We can join "oy" and then "ah", and then "ha" to form the string "oyahha"  which contains the string "ya".  So, the answer is "YES"  Input : str[] = "ha"         words[] = "ah" Output :YES The string "ahah" contains "ha"  as a substring.  Input : str = "hp"        words[] = {"ht", "tp"| Output :NO We can't produce a string containing "hp" as a sub-string. Note that we can join "ht" and then "tp" producing "http", but it doesn't contain the  "hp" as a sub-string.

If we look at the given examples carefully, we can see that our answer will be "YES" if any of the following conditions is true, 

  1. str is equal to any one of the N words
  2. str is equal to reverse of any of the words.
  3. It first letter of str is equal to last letter of any of the given N strings and last letter is equal to the first letter of any of the given N strings.

Otherwise our output will always be NO.

Below is the implementation of the above approach.

C++
// CPP code to check if a two character string can  // be made using given strings #include <bits/stdc++.h> using namespace std;  // Function to check if str can be made using // given words bool makeAndCheckString(vector<string> words, string str) {     int n = words.size();     bool first = false, second = false;      for (int i = 0; i < n; i++) {          // If str itself is present          if (words[i] == str)             return true;              // Match first character of str         // with second of word and vice versa         if (str[0] == words[i][1])              first = true;                     if (str[1] == words[i][0])              second = true;          // If both characters found.         if (first && second)             return true;      }          return false;  }  // Driver Code int main() {      string str = "ya";              vector<string> words = { "ah", "oy", "to", "ha"};          if (makeAndCheckString(words, str))        cout << "Yes";     else        cout << "No";     return 0; } 
Java
// Java code to check if a two character string can  // be made using given strings import java.util.*;  class GFG {  // Function to check if str can be made using // given words static boolean makeAndCheckString(Vector<String> words,                                              String str) {     int n = words.size();     boolean first = false, second = false;      for (int i = 0; i < n; i++)      {          // If str itself is present          if (words.get(i) == str)             return true;              // Match first character of str         // with second of word and vice versa         if (str.charAt(0) == words.get(i).charAt(1))              first = true;                  if (str.charAt(1) == words.get(i).charAt(0))              second = true;          // If both characters found.         if (first && second)             return true;      }          return false;  }  // Driver Code public static void main(String[] args)  {     String str = "ya";      String[] array = { "ah", "oy", "to", "ha"};     Vector<String> words = new Vector<String>(Arrays.asList(array));          if (makeAndCheckString(words, str))         System.out.println("Yes");     else         System.out.println("No"); } }  // This code is contributed by 29AjayKumar 
Python3
# Python3 code to check if a two character string can   # be made using given strings   # Function to check if str can be made using  # given words  def makeAndCheckString(words, str):     n = len(words)     first = second = False      for i in range(n):         # If str itself is present         if words[i]==str:             return True          # Match first character of str          # with second of word and vice versa          if str[0] == words[i][1]:             first = True         if str[1] == words[i][0]:             second = True          # If both characters found.         if first and second:             return True          return False      # Driver Code  str = 'ya' words = ['ah', 'oy', 'to', 'ha'] if makeAndCheckString(words, str):     print('YES') else:     print('NO')  # This code is contributed   # by SamyuktaSHegde  
C#
// C# code to check if a two character string can  // be made using given strings using System;  using System.Collections.Generic;   class GFG {  // Function to check if str can be made using // given words static bool makeAndCheckString(List<String> words,                                              String str) {     int n = words.Count;     bool first = false, second = false;      for (int i = 0; i < n; i++)      {          // If str itself is present          if (words[i] == str)             return true;              // Match first character of str         // with second of word and vice versa         if (str[0] == words[i][1])              first = true;                  if (str[1] == words[i][0])              second = true;          // If both characters found.         if (first && second)             return true;      }          return false;  }  // Driver Code public static void Main(String[] args)  {     String str = "ya";      String[] array = { "ah", "oy", "to", "ha"};     List<String> words = new List<String>(array);          if (makeAndCheckString(words, str))         Console.WriteLine("Yes");     else         Console.WriteLine("No"); } }  // This code is contributed by Princi Singh 
PHP
<?php // PHP code to check if a two character string can  // be made using given strings   // Function to check if str can be made using  // given words  function makeAndCheckString($words, $str)  {     $n = sizeof($words) ;     $first = false ;     $second = false;       for ($i = 0; $i < $n; $i++) {           // If str itself is present          if ($words[$i] == $str)              return true;               // Match first character of str          // with second of word and vice versa          if ($str[0] == $words[$i][1])              $first = true;                      if ($str[1] == $words[$i][0])              $second = true;           // If both characters found.          if ($first && $second)              return true;      }           return false;  }       // Driver Code       $str = "ya";              $words = array( "ah", "oy", "to", "ha") ;     if (makeAndCheckString($words, $str))          echo "Yes";      else         echo "No";       // This code is contributed by Ryuga ?> 
JavaScript
<script>     // Javascript code to check if a two character string can      // be made using given strings          // Function to check if str can be made using     // given words     function makeAndCheckString(words, str)     {         let n = words.length;         let first = false, second = false;          for (let i = 0; i < n; i++)          {              // If str itself is present              if (words[i] == str)                 return true;              // Match first character of str             // with second of word and vice versa             if (str[0] == words[i][1])                  first = true;                      if (str[1] == words[i][0])                  second = true;              // If both characters found.             if (first && second)                 return true;          }          return false;      }          let str = "ya";      let words = [ "ah", "oy", "to", "ha"];         if (makeAndCheckString(words, str))         document.write("YES");     else         document.write("NO");          // This code is contributed by suresh07. </script> 

Output
Yes

Time Complexity: O(n), where n represents the size of the given vector.
Auxiliary Space: O(1), no extra space is required, so it is a constant.


Next Article
Check if characters of a given string can be used to form any N equal strings

S

Sarthak Kohli
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
Practice Tags :
  • Misc
  • Strings

Similar Reads

  • Check if a given string is made up of two alternating characters
    Given a string str, the task is to check whether the given string is made up of only two alternating characters.Examples: Input: str = "ABABABAB" Output: YesInput: str = "XYZ" Output: No Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: In order for the
    11 min read
  • Check if characters of a given string can be used to form any N equal strings
    Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No. Examples: Input: S = "caacbb", N = 2Output: YesExplanation: All possible strings that can be gen
    5 min read
  • Check if two strings can be made equal by swapping one character among each other
    Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the el
    10 min read
  • Check if number of distinct characters in 2 Strings can be made equal
    Given two strings A and B of lowercase English letters of lengths N and M respectively. Check whether the number of distinct characters in both strings A and B can be made equal by applying the operation at most one time. Where operation is: Choose any index i such that 0 ≤ i ≤ N from string A and i
    15 min read
  • Check if string S can be converted to T by incrementing characters
    Given strings S and T. The task is to check if S can be converted to T by performing at most K operations. For the ith operation, select any character in S which has not been selected before, and increment the chosen character i times (i.e., replacing it with the letter i times ahead in the alphabet
    8 min read
  • Check if a given string can be formed using characters of adjacent cells of a Matrix
    Given a matrix board of characters and a string Word, the task is to check if Word exists on the board constructed from a sequence of horizontally and vertically adjacent characters only. Each character can be used only once. Examples: Input: board = { {'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A
    9 min read
  • Find smallest string with whose characters all given Strings can be generated
    Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanati
    5 min read
  • Check if given string can be made Palindrome by removing only single type of character | Set-2
    Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times Examples: Input: S = "abczdzacb"Output: YesExplanation: Remove first and second occurrence of character ‘a’. String S becomes “bczdzcb”, which is a palin
    9 min read
  • Check if there is any common character in two given strings
    Given two strings. The task is to check that is there any common character in between two strings. Examples: Input: s1 = "geeksforgeeks", s2 = "geeks" Output: Yes Input: s1 = "geeks", s2 = "for" Output: No Approach: Traverse the 1st string and map the characters of the string with its frequency, in
    8 min read
  • Check whether second string can be formed from characters of first string
    Given two strings str1 and str2, check if str2 can be formed from str1 Example : Input : str1 = geekforgeeks, str2 = geeksOutput : YesHere, string2 can be formed from string1. Input : str1 = geekforgeeks, str2 = andOutput : NoHere string2 cannot be formed from string1. Input : str1 = geekforgeeks, s
    5 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