713997. String rp or pr

Medium

String rp or pr -- 170647

Summary

The problem is about determining whether a given string can be transformed into either "rp" or "pr" by rearranging its characters. The key concepts involved are strings and greedy algorithms.

Detailed Explanation

The approach to solve this problem is to first count the frequency of each character in the input string. Then, we can check if the string can be transformed into "rp" or "pr". If the number of 'r's is greater than or equal to the number of 'p's and the total count of 'r' and 'p' characters are odd, then the string can be transformed into "rp". Otherwise, it can be transformed into "pr".

Here is a step-by-step breakdown of the solution:

  1. Initialize variables r_count and p_count to 0.
  2. Iterate through each character in the input string.
  3. If the character is 'r', increment r_count. If the character is 'p', increment p_count.
  4. After iterating through all characters, check if r_count >= p_count and (r_count + p_count) % 2 != 0. If both conditions are true, then the string can be transformed into "rp". Otherwise, it can be transformed into "pr".
  5. Return the result as a string ("rp" or "pr").

Time complexity: O(n), where n is the length of the input string. Space complexity: O(1), as we only use a constant amount of space to store the counts.

Optimized Solutions

Java

View on GeeksforGeeks
public String rpOrPr(String s) {
    int r_count = 0;
    int p_count = 0;

    for (char c : s.toCharArray()) {
        if (c == 'r') {
            r_count++;
        } else if (c == 'p') {
            p_count++;
        }
    }

    return r_count >= p_count && (r_count + p_count) % 2 != 0 ? "rp" : "pr";
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.