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 DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Check if it is possible to rearrange a binary string with alternate 0s and 1s
Next article icon

Check if it is possible to transform one string to another

Last Updated : 05 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two strings s1 and s2(all letters in uppercase). Check if it is possible to convert s1 to s2 by performing following operations.

  1.  Make some lowercase letters uppercase. 
  2. Delete all the lowercase letters. 

Examples:  

Input : s1 = daBcd s2 = ABC  Output : yes Explanation : daBcd -> dABCd -> ABC   Convert a and b at index 1 and 3 to  upper case, delete the rest those are  lowercase. We get the string s2.   Input : s1 = argaju    s2 = RAJ Output : yes  Explanation : argaju -> aRgAJu -> RAJ   convert index 1, 3 and 4 to uppercase  and then delete. All lowercase letters  Input : s1 = ABcd s2= BCD  Output : NO
Recommended Practice
String Conversion
Try It! 

Approach: 

Let DPi, j be 1 if it is possible to convert 1st i characters of s1 to j characters of s2, else DPi, j=0. Close observations gives us two conditions to deal with. 
Initially DP0, 0=1, if DPi, j=1 then it is possible to check for next sets using following conditions. 

  1. If s1[i] in upper case is equal to s2[j] then it is possible to convert i+1 characters of s1 to j+1 characters of s2, hence DPi+1, j+1=1.
  2. If s1[i] is in lower case, then it is possible to delete that element and hence i+1 characters can be converted to j characters of s2. Hence DPi+1, j=1. 

If DPn, m=1, then it is possible to convert s1 to s2 by following conditions. 

Below is the CPP illustration of the above approach.  

C++




// cpp program to check if a string can
// be converted to another string by
// performing operations
#include <bits/stdc++.h>
using namespace std;
 
// function to check if a string can be
// converted to  another string by
// performing following operations
bool check(string s1, string s2)
{
    // calculates length
    int n = s1.length();
    int m = s2.length();
 
    bool dp[n + 1][m + 1];
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            dp[i][j] = false;
        }
    }
    // mark 1st position as true
    dp[0][0] = true;
 
    // traverse for all DPi, j
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j <= s2.length(); j++) {
 
            // if possible for to convert i
            // characters of s1 to j characters
            // of s2
            if (dp[i][j]) {
 
                // if upper_case(s1[i])==s2[j]
                // is same
                if (j < s2.length() &&
                    (toupper(s1[i]) == s2[j]))
                    dp[i + 1][j + 1] = true;
 
                // if not upper then deletion is
                // possible
                if (!isupper(s1[i]))
                    dp[i + 1][j] = true;
            }
        }
    }
 
    return (dp[n][m]);
}
 
// driver code
int main()
{
    string s1 = "daBcd";
    string s2 = "ABC";
 
    if (check(s1, s2))
        cout << "YES";
    else
        cout << "NO";
 
    return 0;
}
 
 

Java




// Java program to check if a string can
// be converted to another string by
// performing operations
import java.io.*;
 
class GFG {
     
    // function to check if a string can be
    // converted to another string by
    // performing following operations
    static boolean check(String s1, String s2)
    {
        // calculates length
        int n = s1.length();
        int m = s2.length();
     
        boolean dp[][]=new boolean[n + 1][m + 1];
        for (int i = 0; i <= n; i++)
        {
            for (int j = 0; j <= m; j++)
            {
                dp[i][j] = false;
            }
        }
        // mark 1st position as true
        dp[0][0] = true;
     
        // traverse for all DPi, j
        for (int i = 0; i < s1.length(); i++)
        {
            for (int j = 0; j <= s2.length(); j++)
            {
     
                // if possible for to convert i
                // characters of s1 to j characters
                // of s2
                if (dp[i][j]) {
     
                    // if upper_case(s1[i])==s2[j]
                    // is same
                    if (j < s2.length() &&
                        (Character.toUpperCase(s1.charAt(i)) == s2.charAt(j)))
                        dp[i + 1][j + 1] = true;
     
                    // if not upper then deletion is
                    // possible
                    if (!Character.isUpperCase(s1.charAt(i)))
                        dp[i + 1][j] = true;
                }
            }
        }
     
        return (dp[n][m]);
    }
     
    // driver code
    public static void main(String args[])
    {
        String s1 = "daBcd";
        String s2 = "ABC";
     
        if (check(s1, s2))
            System.out.println("YES");
        else
            System.out.println("NO");
     
    }
}
 
// This code is contributed by Nikita Tiwari.
 
 

Python3




# Python3 program to check if a string can
# be converted to another string by
# performing operations
 
 
# function to check if a string can be
# converted to another string by
# performing following operations
def check(s1,s2):
     
    # calculates length
    n = len(s1)
    m = len(s2)
    dp=([[False for i in range(m+1)]
       for i in range(n+1)])
     
    # mark 1st position as true
    dp[0][0] = True
     
    # traverse for all DPi, j
    for i in range(len(s1)):
        for j in range(len(s2)+1):
             
            # if possible for to convert i
            # characters of s1 to j characters
            # of s2
            if (dp[i][j]):
                 
                # if upper_case(s1[i])==s2[j]
                # is same
                if ((j < len(s2) and
                   (s1[i].upper()== s2[j]))):
                    dp[i + 1][j + 1] = True
                     
                # if not upper then deletion is
                # possible
                if (s1[i].isupper()==False):
                    dp[i + 1][j] = True
    return (dp[n][m])
 
# driver code
if __name__=='__main__':
 
    s1 = "daBcd"
    s2 = "ABC"
    if (check(s1, s2)):
        print("YES")
    else:
        print("NO")
 
# this code is contributed by
# sahilshelangia
 
 

C#




// C# program to check if a string can
// be converted to another string by
// performing operations
using System;
 
class GFG
{
 
// function to check if a string can be
// converted to another string by
// performing following operations
static bool check(string s1, string s2)
{
    // calculates length
    int n = s1.Length;
    int m = s2.Length;
 
    bool[,] dp = new bool[n + 1, m + 1];
    for (int i = 0; i <= n; i++)
    {
        for (int j = 0; j <= m; j++)
        {
            dp[i, j] = false;
        }
    }
     
    // mark 1st position as true
    dp[0, 0] = true;
 
    // traverse for all DPi, j
    for (int i = 0; i < s1.Length; i++)
    {
        for (int j = 0; j <= s2.Length; j++)
        {
 
            // if possible for to convert i
            // characters of s1 to j characters
            // of s2
            if (dp[i, j])
            {
 
                // if upper_case(s1[i])==s2[j]
                // is same
                if (j < s2.Length &&
                    (Char.ToUpper(s1[i]) == s2[j]))
                    dp[i + 1, j + 1] = true;
 
                // if not upper then deletion is
                // possible
                if (!Char.IsUpper(s1[i]))
                    dp[i + 1, j] = true;
            }
        }
    }
 
    return (dp[n, m]);
}
 
// Driver Code
public static void Main()
{
    string s1 = "daBcd";
    string s2 = "ABC";
 
    if (check(s1, s2))
        Console.Write("YES");
    else
        Console.Write("NO");
}
}
 
// This code is contributed
// by ChitraNayal
 
 

Javascript




<script>
// Javascript program to check if a string can
// be converted to another string by
// performing operations
     
     
    // function to check if a string can be
    // converted to another string by
    // performing following operations
    function check(s1,s2)
    {
        // calculates length
        let n = s1.length;
        let m = s2.length;
       
        let dp=new Array(n + 1);
        for (let i = 0; i <= n; i++)
        {
            dp[i]=new Array(m+1);
            for (let j = 0; j <= m; j++)
            {
                dp[i][j] = false;
            }
        }
        // mark 1st position as true
        dp[0][0] = true;
       
        // traverse for all DPi, j
        for (let i = 0; i < s1.length; i++)
        {
            for (let j = 0; j <= s2.length; j++)
            {   
                 
       
                // if possible for to convert i
                // characters of s1 to j characters
                // of s2
                if (dp[i][j]) {
       
                    // if upper_case(s1[i])==s2[j]
                    // is same
                    if (j < s2.length &&
                        (s1[i].toUpperCase() == s2[j]))
                        dp[i + 1][j + 1] = true;
       
                    // if not upper then deletion is
                    // possible
                     
                    if (!(s1[i] == s1[i].toUpperCase()))
                        dp[i + 1][j] = true;
                }
            }
        }
       
        return (dp[n][m]);
    }
     
    // driver code
    let s1 = "daBcd";
    let s2 = "ABC";
    if (check(s1, s2))
        document.write("YES");
    else
        document.write("NO");
 
     
     
    // This code is contributed by avanitrachhadiya2155
</script>
 
 
Output
YES

Time Complexity: O(N*M) where N and M are the lengths of the strings.
Auxiliary Space: O(N*M)



Next Article
Check if it is possible to rearrange a binary string with alternate 0s and 1s

S

Striver
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Strings
Practice Tags :
  • Dynamic Programming
  • Strings

Similar Reads

  • Check if it is possible to convert one string into another with given constraints
    Given two strings contains three characters i.e 'A', 'B 'and '#' only. Check is it possible to convert first string into another string by performing following operations on string first. 'A' can move towards Left only 'B' can move towards Right only Neither 'A' nor 'B' cross each other If it is pos
    8 min read
  • Check if a string can be transformed to another by sorting substrings
    Given two strings str1 and str2, each of length N and consisting of lowercase English alphabets only, the task is to check if string str1 can be transformed to string str2 by performing the following operations any number of times. Choose a non-empty substring in str1 and sort it in-place lexicograp
    7 min read
  • Check if a string is a scrambled form of another string
    Given two strings s1 and s2 of equal length, the task is to determine if s2 is a scrambled version of s1. A scrambled string is formed by recursively splitting the string into two non-empty substrings and rearranging them randomly (s = x + y or s = y + x) and then recursively scramble the two substr
    15+ min read
  • Transform One String to Another using Minimum Number of Given Operation
    Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it's possible to convert the string. If yes, then output minimum no. of operations required for transformation. Examples: Input: A = "ABD",
    15+ min read
  • Check if it is possible to rearrange a binary string with alternate 0s and 1s
    Given a binary string of length, at least two. We need to check if it is possible to rearrange a binary string such that there are alternate 0s and 1s. If possible, then the output is YES, otherwise the output is NO. Examples: Input : 1011 Output : NO We can't rearrange the string such that it has a
    5 min read
  • Check if it is possible to form string B from A under the given constraints
    Given two strings A and B and two integers b and m. The task is to find that if it is possible to form string B from A such that A is divided into groups of b characters except the last group which will have characters ? b and you are allowed to pick atmost m characters from each group, and also ord
    9 min read
  • Check if a given string can be converted to another by given possible swaps
    Given two strings str1 and str2, the task is to check if a string str1 can be converted to string str2 by performing the following operations any number of times: Swap any two characters of str1.Swap all the occurrences of a character of str1 to all occurrences of any other distinct character of str
    8 min read
  • Transform the given String into two same Strings by removing at most one character
    Given a string S of length N where (N ? 1). The task is to check whether by removing at most one character from the given string it can be divided into two same sub-strings or not return YES or NO for possibilities. Examples: Input: N = 5, S = abzabOutput: YESExplanation: Character 'z' at index 3 ca
    9 min read
  • Transform an Empty String to a Given String
    Given a string s1 and an empty string s2, you have to transform the empty string s2 to given string s1 using the given moves. In one move, you can create a sequence of identical characters on string s2 or overwrite any substring with a new character on string s2. The task is to minimize the number o
    7 min read
  • Meta Strings (Check if two strings can become same after a swap in one string)
    Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input: s1 = "geeks" , s2 = "keegs"Output: TrueExplana
    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