Open In App

Check if Strings Are Rotations of Each Other

Last Updated : 25 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two string s1 and s2 of same length, the task is to check whether s2 is a rotation of s1.

Examples: 

Input: s1 = “abcd”, s2 = “cdab”
Output: true
Explanation: After 2 right rotations, s1 will become equal to s2.

Input: s1 = “aab”, s2 = “aba”
Output: true
Explanation: After 1 left rotation, s1 will become equal to s2.

Input: s1 = “abcd”, s2 = “acbd”
Output: false
Explanation: Strings are not rotations of each other.

[Naive Approach] Generating all rotations – O(n^2) Time and O(1) Space

The idea is to generate all possible rotations of the first string and check if any of these rotations match the second string. If any rotation matches, the two strings are rotations of each other, otherwise they are not.

C++
// C++ program to check two string for rotation
// by generating all rotations

#include <iostream>
using namespace std;

// Function to check if s1 and s2 are rotations of each other
bool areRotations(string &s1, string &s2) {
    int n = s1.size();
      
      // generate and check all possible rotations of s1
    for (int i = 0; i < n; ++i) {
      
          // if current rotation is equal to s2 return true
        if (s1 == s2)
            return true;
      
          // right rotate s1
        char last = s1.back();
        s1.pop_back();
        s1 = last + s1;
    }
    return false;
}

int main() {
    string s1 = "aab";
    string s2 = "aba";

    cout << (areRotations(s1, s2) ? "true" : "false");
    return 0;
}
C
// C program to check two strings for rotation
// by generating all rotations
#include <stdio.h>
#include <string.h>

// Function to check if s1 and s2 are rotations of each other
int areRotations(char s1[], char s2[]) {
    int n = strlen(s1);

    // Generate and check all possible rotations of s1
    for (int i = 0; i < n; ++i) {
        
        // If current rotation is equal to s2, return true
        if (strcmp(s1, s2) == 0)
            return 1;

        // Right rotate s1
        char last = s1[n-1];
        for (int j = n-1; j > 0; j--) {
            s1[j] = s1[j-1];
        }
        s1[0] = last;
    }
    return 0;
}

int main() {
    char s1[] = "aab";
    char s2[] = "aba";

    printf("%s", areRotations(s1, s2) ? "true" : "false");
    return 0;
}
Java
// Java program to check two strings for rotation
// by generating all rotations
class GfG {
    
    // Function to check if s1 and s2 are rotations of each other
    static boolean areRotations(String s1, String s2) {
        int n = s1.length();

        // Generate and check all possible rotations of s1
        for (int i = 0; i < n; ++i) {
            
            // If current rotation is equal to s2, return true
            if (s1.equals(s2)) {
                return true;
            }

            // Right rotate s1
            char last = s1.charAt(s1.length() - 1);
            s1 = last + s1.substring(0, s1.length() - 1);
        }
        return false;
    }

    public static void main(String[] args) {
        String s1 = "aab";
        String s2 = "aba";

        System.out.println(areRotations(s1, s2));
    }
}
Python
# Python program to check two strings for rotation
# by generating all rotations

# Function to check if s1 and s2 are rotations of each other
def areRotations(s1, s2):
    n = len(s1)

    # Generate and check all possible rotations of s1
    for _ in range(n):
        
        # If current rotation is equal to s2, return true
        if s1 == s2:
            return True

        # Right rotate s1
        s1 = s1[-1] + s1[:-1]

    return False

if __name__ == "__main__":
    s1 = "aab"
    s2 = "aba"

    print("true" if areRotations(s1, s2) else "false")
C#
// C# program to check two strings for rotation
// by generating all rotations
using System;

class GfG {

    // Function to check if s1 and s2 are rotations of each other
    static bool areRotations(string s1, string s2) {
        int n = s1.Length;

        // Generate and check all possible rotations of s1
        for (int i = 0; i < n; ++i) {
            
            // If current rotation is equal to s2, return true
            if (s1 == s2) {
                return true;
            }

            // Right rotate s1
            char last = s1[s1.Length - 1];
            s1 = last + s1.Substring(0, s1.Length - 1);
        }
        return false;
    }

    static void Main() {
        string s1 = "aab";
        string s2 = "aba";

        Console.WriteLine(areRotations(s1, s2) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check two strings for rotation
// by generating all rotations

// Function to check if s1 and s2 are rotations of each other
function areRotations(s1, s2) {
    let n = s1.length;

    // Generate and check all possible rotations of s1
    for (let i = 0; i < n; i++) {
        
        // If current rotation is equal to s2, return true
        if (s1 === s2) {
            return true;
        }

        // Right rotate s1
        let last = s1[s1.length - 1];
        s1 = last + s1.slice(0, s1.length - 1);
    }
    return false;
}

// Driver Code
let s1 = "aab";
let s2 = "aba";

console.log(areRotations(s1, s2) ? "true" : "false");

Output
true

[Expected Approach] Using KMP Algorithm – O(n) Time and O(n) Space

The idea is that when a string is concatenated with itself, all possible rotations of the string will naturally appear as substrings within this concatenated string. To determine if another string is a rotation of the first, we can use KMP Algorithm to check if the second string exists as a substring in the concatenated form of the first string.


C++
// C++ program to check if two given strings
// are rotations of each other using KMP Algorithm

#include <iostream>
#include <vector>
using namespace std;

vector<int> computeLPSArray(string& pat) {
      int n = pat.size();
      vector<int> lps(n);
  
    // Length of the previous longest prefix suffix
    int len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    // loop calculates lps[i] for i = 1 to n-1
    int i = 1;
    while (i < n) {
      
        // If the characters match, increment len 
        // and extend the matching prefix
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
      
        // If there is a mismatch
        else {
          
            // If len is not zero, update len to
            // last known prefix length
            if (len != 0) {
                len = lps[len - 1];
            }
          
            // No prefix matches, set lps[i] = 0
            // and move to the next character
            else {
                lps[i] = 0;
                i++;
            }
        }
    }
      return lps;
}


// Function to check if s1 and s2 are rotations of each other
bool areRotations(string &s1, string &s2) {
      string txt = s1 + s1;
      string pat = s2;
      
      // search the pattern string s2 in the concatenation string 
      int n = txt.length();
    int m = pat.length();

    // Create lps[] that will hold the longest prefix suffix
    // values for pattern
    vector<int> lps = computeLPSArray(pat);
  
    int i = 0; 
    int j = 0;
    while (i < n) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }

        if (j == m) {
            return true;
        }

        // Mismatch after j matches
        else if (i < n && pat[j] != txt[i]) {

            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
    return false;
}

int main() {
    string s1 = "aab"; 
      string s2 = "aba";
      
    cout << (areRotations(s1, s2) ? "true" : "false");
}
C
// C program to check if two given strings are
// rotations of  each other using KMP Algorithm

#include <stdio.h>
#include <string.h>

int* computeLPSArray(char* pat) {
    int n = strlen(pat);
    int* lps = (int*)malloc(n * sizeof(int));
  
    // Length of the previous longest prefix suffix
    int len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    // loop calculates lps[i] for i = 1 to n-1
    int i = 1;
    while (i < n) {
      
        // If the characters match, increment len 
        // and extend the matching prefix
        if (pat[i] == pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
      
        // If there is a mismatch
        else {
          
            // If len is not zero, update len to
            // last known prefix length
            if (len != 0) {
                len = lps[len - 1];
            }
          
            // No prefix matches, set lps[i] = 0
            // and move to the next character
            else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}


// Function to check if s1 and s2 are rotations of each other
int areRotations(char *s1, char *s2) {
    char* txt = (char*)malloc(strlen(s1) * 2 + 1);
    strcpy(txt, s1);
    strcat(txt, s1);
    
    char* pat = s2;
    
    // search the pattern string s2 in the concatenated string 
    int n = strlen(txt);
    int m = strlen(pat);

    // Create lps[] that will hold the longest prefix suffix
    // values for pattern
    int* lps = computeLPSArray(pat);
  
    int i = 0; 
    int j = 0;
    while (i < n) {
        if (pat[j] == txt[i]) {
            j++;
            i++;
        }

        if (j == m) {
            return 1; 
        }

        // Mismatch after j matches
        else if (i < n && pat[j] != txt[i]) {

            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
    return 0;
}

int main() {
    char s1[] = "aab"; 
    char s2[] = "aba";
    
    printf("%s", (areRotations(s1, s2) ? "true" : "false"));
    return 0;
}
Java
// Java program to check if two given strings are rotations 
// of each other using KMP Algorithm

import java.util.Arrays;

class GfG {
    
    static int[] computeLPSArray(String pat) {
        int n = pat.length();
        int[] lps = new int[n];
      
        // Length of the previous longest prefix suffix
        int len = 0;

        // lps[0] is always 0
        lps[0] = 0;

        // loop calculates lps[i] for i = 1 to n-1
        int i = 1;
        while (i < n) {
          
            // If the characters match, increment len 
            // and extend the matching prefix
            if (pat.charAt(i) == pat.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }
          
            // If there is a mismatch
            else {
              
                // If len is not zero, update len to
                // last known prefix length
                if (len != 0) {
                    len = lps[len - 1];
                }
              
                // No prefix matches, set lps[i] = 0
                // and move to the next character
                else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }

    // Function to check if s1 and s2 are rotations of each other
    static boolean areRotations(String s1, String s2) {
        String txt = s1 + s1;
        String pat = s2;
        
        // search the pattern string s2 in the concatenation string 
        int n = txt.length();
        int m = pat.length();

        // Create lps[] that will hold the longest prefix suffix
        // values for pattern
        int[] lps = computeLPSArray(pat);
      
        int i = 0; 
        int j = 0;
        while (i < n) {
            if (pat.charAt(j) == txt.charAt(i)) {
                j++;
                i++;
            }

            if (j == m) {
                return true;
            }

            // Mismatch after j matches
            else if (i < n && pat.charAt(j) != txt.charAt(i)) {

                // Do not match lps[0..lps[j-1]] characters,
                // they will match anyway
                if (j != 0)
                    j = lps[j - 1];
                else
                    i = i + 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String s1 = "aab"; 
        String s2 = "aba";
        
        System.out.println(areRotations(s1, s2) ? "true" : "false");
    }
}
Python
# Python program to check if two given strings are 
# rotations of each other using KMP Algorithm 

def computeLPSArray(pat):
    n = len(pat)
    lps = [0] * n
  
    # Length of the previous longest prefix suffix
    patLen = 0

    # lps[0] is always 0
    lps[0] = 0

    # loop calculates lps[i] for i = 1 to n-1
    i = 1
    while i < n:
      
        # If the characters match, increment len 
        # and extend the matching prefix
        if pat[i] == pat[patLen]:
            patLen += 1
            lps[i] = patLen
            i += 1
      
        # If there is a mismatch
        else:
          
            # If len is not zero, update len to
            # last known prefix length
            if patLen != 0:
                patLen = lps[patLen - 1]
            # No prefix matches, set lps[i] = 0
            # and move to the next character
            else:
                lps[i] = 0
                i += 1
    return lps


# Function to check if s1 and s2 are rotations of each other
def areRotations(s1, s2):
    txt = s1 + s1
    pat = s2
    
    # search the pattern string s2 in the concatenation string 
    n = len(txt)
    m = len(pat)

    # Create lps[] that will hold the longest prefix suffix
    # values for pattern
    lps = computeLPSArray(pat)
  
    i = 0 
    j = 0
    while i < n:
        if pat[j] == txt[i]:
            j += 1
            i += 1

        if j == m:
            return True

        # Mismatch after j matches
        elif i < n and pat[j] != txt[i]:
            # Do not match lps[0..lps[j-1]] characters,
            # they will match anyway
            if j != 0:
                j = lps[j - 1]
            else:
                i += 1
    return False

if __name__ == "__main__":
    s1 = "aab" 
    s2 = "aba"
    
    print("true" if areRotations(s1, s2) else "false")
C#
// C# program to check if two given strings are rotations
// of each other using KMP Algorithm

using System;
using System.Collections.Generic;

class GfG {
    static int[] ComputeLPSArray(string pat) {
        int n = pat.Length;
        int[] lps = new int[n];
  
        // Length of the previous longest prefix suffix
        int len = 0;

        // lps[0] is always 0
        lps[0] = 0;

        // loop calculates lps[i] for i = 1 to n-1
        int i = 1;
        while (i < n) {
          
            // If the characters match, increment len 
            // and extend the matching prefix
            if (pat[i] == pat[len]) {
                len++;
                lps[i] = len;
                i++;
            }
            
            // If there is a mismatch
            else {
                
                // If len is not zero, update len to
                // last known prefix length
                if (len != 0) {
                    len = lps[len - 1];
                }
                
                // No prefix matches, set lps[i] = 0
                // and move to the next character
                else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }

    // Function to check if s1 and s2 are rotations of each other
    static bool AreRotations(string s1, string s2) {
        string txt = s1 + s1;
        string pat = s2;
        
        // search the pattern string s2 in the concatenation string 
        int n = txt.Length;
        int m = pat.Length;

        // Create lps[] that will hold the longest prefix suffix
        // values for pattern
        int[] lps = ComputeLPSArray(pat);
  
        int i = 0; 
        int j = 0;
        while (i < n) {
            if (pat[j] == txt[i]) {
                j++;
                i++;
            }

            if (j == m)  {
                return true;
            }

            // Mismatch after j matches
            else if (i < n && pat[j] != txt[i]) {
              
                // Do not match lps[0..lps[j-1]] characters,
                // they will match anyway
                if (j != 0)
                    j = lps[j - 1];
                else
                    i++;
            }
        }
        return false;
    }

    static void Main() {
        string s1 = "aab"; 
        string s2 = "aba";
        
        Console.WriteLine(AreRotations(s1, s2) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if two given strings
// are rotations of each other using KMP Algorithm

function computeLPSArray(pat) {
    let n = pat.length;
    let lps = new Array(n).fill(0);
  
    // Length of the previous longest prefix suffix
    let len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    // loop calculates lps[i] for i = 1 to n-1
    let i = 1;
    while (i < n) {
      
        // If the characters match, increment len 
        // and extend the matching prefix
        if (pat[i] === pat[len]) {
            len++;
            lps[i] = len;
            i++;
        }
      
        // If there is a mismatch
        else {
          
            // If len is not zero, update len to
            // last known prefix length
            if (len !== 0) {
                len = lps[len - 1];
            }
          
            // No prefix matches, set lps[i] = 0
            // and move to the next character
            else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

// Function to check if s1 and s2 are rotations of each other
function areRotations(s1, s2) {
    let txt = s1 + s1;
    let pat = s2;
    
    // search the pattern string s2 in the concatenation string 
    let n = txt.length;
    let m = pat.length;

    // Create lps[] that will hold the longest prefix suffix
    // values for pattern
    let lps = computeLPSArray(pat);
  
    let i = 0; 
    let j = 0;
    while (i < n) {
        if (pat[j] === txt[i]) {
            j++;
            i++;
        }

        if (j === m) {
            return true;
        }

        // Mismatch after j matches
        else if (i < n && pat[j] !== txt[i]) {

            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j !== 0)
                j = lps[j - 1];
            else
                i++;
        }
    }
    return false;
}

// Driver Code
const s1 = "aab"; 
const s2 = "aba";

console.log(areRotations(s1, s2) ? "true" : "false");

Output
true

[Alternate Approach] Using Built-in Method

This approach is similar to the previous approach, but here we are using built-in methods to find a pattern string inside other string.

C++
// C++ program to check if two given strings
// are rotations of  each other
#include <iostream>
using namespace std;

// Function to check if s1 and s2 are rotations of each other
bool areRotations(string &s1, string &s2) {
      s1 += s1;
  
      // find s2 in concatenated string
      return s1.find(s2) != string::npos;
}

int main() {
    string s1 = "aab"; 
      string s2 = "aba";
      
    cout << (areRotations(s1, s2) ? "true" : "false");
}
C
// C program to check if two given strings are rotations of each other
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// Function to check if s1 and s2 are rotations of each other
int areRotations(char* s1, char* s2) {
  
    // Concatenate s1 with itself
    int len = strlen(s1);
    char* concat = (char*)malloc(2 * len + 1);
    strcpy(concat, s1);
    strcat(concat, s1);

    // find s2 in concatenated string
    int result = strstr(concat, s2) != NULL;
    free(concat);
    return result;
}

int main() {
    char s1[] = "aab";
    char s2[] = "aba";

    printf("%s\n", areRotations(s1, s2) ? "true" : "false");
    return 0;
}
Java
// Java program to check if two given strings are rotations of each other
class GfG {

    // Function to check if s1 and s2 are rotations of each other
    static boolean areRotations(String s1, String s2) {
        s1 = s1 + s1;

        // find s2 in concatenated string
        return s1.contains(s2);
    }

    public static void main(String[] args) {
        String s1 = "aab";
        String s2 = "aba";

        System.out.println(areRotations(s1, s2));
    }
}
Python
# Python program to check if two given strings are rotations of each other

# Function to check if s1 and s2 are rotations of each other
def areRotations(s1, s2):
    s1 = s1 + s1

    # find s2 in concatenated string
    return s2 in s1

if __name__ == "__main__":
    s1 = "aab"
    s2 = "aba"

    print("true" if areRotations(s1, s2) else "false")
C#
// C# program to check if two given strings are rotations of each other
using System;

class GfG {

    // Function to check if s1 and s2 are rotations of each other
    static bool areRotations(string s1, string s2) {
        s1 = s1 + s1;

        // find s2 in concatenated string
        return s1.Contains(s2);
    }

    static void Main() {
        string s1 = "aab";
        string s2 = "aba";

        Console.WriteLine(areRotations(s1, s2) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if two given strings are rotations of each other

// Function to check if s1 and s2 are rotations of each other
function areRotations(s1, s2) {
    s1 += s1;

    // find s2 in concatenated string
    return s1.includes(s2);
}

// driver code
const s1 = "aab";
const s2 = "aba";

console.log(areRotations(s1, s2) ? "true" : "false");

Output
true

Note: Time complexity of built-in methods differs in different languages.



Unlock your potential with our DSA Self-Paced course, designed to help you master Data Structures and Algorithms at your own pace. In 90 days, you’ll learn the core concepts of DSA, tackle real-world problems, and boost your problem-solving skills, all at a speed that fits your schedule. With comprehensive lessons and practical exercises, this course will set you up for success in technical interviews and beyond.

And here's the challenge – join the Three 90 Challenge! Complete 90% of the course in 90 days, and you’ll earn a 90% refund. It's a great way to stay motivated, track your progress, and reward yourself for your dedication. Start the challenge today, and push your limits to achieve mastery in DSA!


Next Article
Article Tags :
Practice Tags :

Similar Reads

Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest proper prefix which is also suffix) constructi
6 min read
POTD Solutions | 14 Nov'23 | Check if strings are rotations of each other or not
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of String but will also help you build up problem-solving skills. We recommend you to try this problem on ou
3 min read
Javascript Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABAOutput : TrueInput : GEEKS, EKSGEOutput : TrueWe have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest proper prefix which is also suffix) construction,
2 min read
Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1 Output: Yes All rows are rotated permutation of each other. Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2 Output: No Explanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2,
8 min read
Check if two numbers are bit rotations of each other or not
Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input : a = 8, b = 1Output : yesExplanation : Representati
6 min read
Javascript Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1Output: YesAll rows are rotated permutationof each other.Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2Output: NoExplanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2, 3The i
2 min read
Javascript Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input : a = 8, b = 1Output : yesExplanation : Representati
3 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 elements which are the same and have the same index
10 min read
Check if two given strings are isomorphic to each other | Set 2 (Using STL)
Given two strings str1 and str2, the task is to check if the two strings are isomorphic to each other. Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in ‘str1’ map to the same character in ‘str2’. Examples: Input:
6 min read
Check whether two strings are anagrams of each other using unordered_map in C++
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can also be used to find if any two given strings are
3 min read
Check if two strings are permutation of each other
Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that you click here and practice it, before moving on
14 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Check if two Strings are Anagrams of each other
Given two strings s1 and s2 consisting of lowercase characters, the task is to check whether the two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. Examples: Input: s1 = “geeks” s2 = “kseeg”Output: trueExplanation: Both the s
13 min read
Minimize count of given operations required to make two given strings permutations of each other
Given two strings str1 and str2, the task is to count the minimum number of operations of the following three types on one of the two strings that are required to make str1 and str2 permutations of each other: Insert a character into the string.Remove a character from the string.Replace a character with another character from the string.Note: All t
13 min read
Form a number using bit rotations of N having same frequency of each digit
Given a number N, the task is to convert it into a number in which all distinct digits have the same frequency, by rotating its bits either clockwise or anti-clockwise. If it is not possible to convert the number print -1, otherwise print the number Examples: Input: N = 331Output: 421Explanation: Binary representation of 331: 101001011After an anti
7 min read
Number of strings which starts and ends with same character after rotations
Given a string str, the task is to find the number of strings that start and end with the same character after a rotation at every possible index of the given string. Examples: Input: str = "GeeksforGeeks" Output: 2 Explanation: All possible strings with rotations at every index are: "GeeksforGeeks", "eeksforGeeksG", "eksforGeeksGe", "ksforGeeksGee
4 min read
Minimum rotations required to delete both Strings
Given two strings A and B which are permutations of each other. The task is to find the minimum number of rotations required to delete both strings completely. We can delete the first characters of both strings if they are the same. Otherwise, the string is rotated one position to left. Examples: Input: A = "abcd", B = "bcda"Output: 1Explanation: r
11 min read
Check if two trees are mirror of each other using level order traversal
Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not.Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Trees in the above figure are mirrors of each other. A recursive solution and an iterative method u
12 min read
Check if bits in range L to R of two numbers are complement of each other or not
Given two non-negative numbers a and b and two values l and r. The problem is to check whether all bits at corresponding positions in the range l to r in both the given numbers are complement of each other or not. The bits are numbered from right to left, i.e., the least significant bit is considered to be at first position.Examples: Input: a = 10,
8 min read
Check if every pair of 1 in the array is at least K length apart from each other
Given a binary array and an integer K, check if every pair of 1 in the array is at least K length apart from each other. Return true if the condition holds, otherwise return false. Examples: Input: arr = [1, 0, 0, 0, 1, 0, 0, 1, 0, 0], K = 2. Output: True Explanation: Every 1 in the array is at least K distance apart from each other. Input: arr= [1
5 min read
Check if all the pairs of an array are coprime with each other
Given an array arr[], the task is to check if all the pairs of an array are coprime to each other. All pairs of an array are coprime when GCD(arr[i], arr[j]) = 1 holds for every pair (i, j), such that 1? i < j ? N. Examples: Input: arr[] = {1, 3, 8}Output: YesExplanation:Here, GCD(arr[0], arr[1]) = GCD(arr[0], arr[2]) = GCD(arr[1], arr[2]) = 1He
11 min read
Check if given Trees can be made mirror images of each other in K swaps
Given two binary tree with same structure but may have different arrangement of value and given an integer K. The task is to check that after exactly K swap on first tree, will it become mirror of second one. In one swap we take two node of same parent and swap its left and right subtree. Examples: Input: K = 1 1 1 / \ / \ 2 3 2 3Output: Yes Input:
11 min read
Check if two arrays are permutations of each other
Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4}Output: NoWe strongly recommend you to minimize your browser and try
15+ min read
Check if two arrays are permutations of each other using Mathematical Operation
Given two unsorted arrays of same size where arr[i] >= 0 for all i, the task is to check if two arrays are permutations of each other or not. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5} arr2[] = {3, 2, 2, 4}Output: NoRecommended: Please try your approach on {IDE} first, be
10 min read
Check if two Linked Lists are permutations of each other
Given two singly Linked list of integer data. The task is to write a program that efficiently checks if two linked lists are permutations of each other. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 2 -> 1 -> 3 -> 5 -> 4Output: YesInput: 10 -> 20 -> 30 -> 40 20 -> 50 -> 60 -> 70Output: NoApproach: Do the following
15+ min read
Check if roots of a Quadratic Equation are reciprocal of each other or not
Given three numbers A, B, C which represents the coefficients(constants) of a quadratic equation [Tex]Ax^{2} + Bx + C = 0 [/Tex], the task is to check whether the roots of the equation represented by these constants are reciprocal of each other or not.Examples: Input: A = 2, B = -5, C = 2 Output: Yes Explanation: The given quadratic equation is [Te
8 min read
Check if two Integer are anagrams of each other
Given two integers A and B, the task is to check whether the given numbers are anagrams of each other or not. Just like strings, a number is said to be an anagram of some other number if it can be made equal to the other number by just shuffling the digits in it.Examples: Input: A = 204, B = 240 Output: Yes Input: A = 23, B = 959 Output: No Recomme
15+ min read
Check if two given circles touch or intersect each other
There are two circles A and B with their centres C1(x1, y1) and C2(x2, y2) and radius R1 and R2. The task is to check both circles A and B touch each other or not. Examples : Input : C1 = (3, 4) C2 = (14, 18) R1 = 5, R2 = 8Output : Circles do not touch each other. Input : C1 = (2, 3) C2 = (15, 28) R1 = 12, R2 = 10Output : Circles intersect with eac
5 min read
Iterative method to check if two trees are mirror of each other
Given two Binary Trees, the task is to check if two trees are mirrors of each other or not. For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true: Their root node’s key must be sameLeft subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.Right subtree of ‘a’ and left subtree of ‘b’ are mirror.Example
10 min read
Check if given string can be formed by two other strings or their permutations
Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pairs from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" which can be rearranged as "amazon". Input: str = "ge
13 min read
  翻译: