LeetCode 484: Find Permutation Solution

Master LeetCode problem 484 (Find Permutation), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

484. Find Permutation

Problem Explanation

Explanation:

This problem asks us to find a permutation that is lexicographically smaller than the given string. We can solve this problem by observing that we can always construct a lexicographically smaller permutation by starting with a sorted sequence of integers from 1 to n and then reversing a subarray within this sequence.

Here is the step-by-step algorithm:

  1. Initialize a list containing integers from 1 to n in ascending order.
  2. For each character in the input string, if it is 'D', reverse a subarray starting from the current index in the list.
  3. Return the list as the final permutation.

Time complexity: O(n) Space complexity: O(n)

:

Solution Code

class Solution {
    public int[] findPermutation(String s) {
        int n = s.length() + 1;
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = i + 1;
        }
        
        for (int i = 0; i < n - 1; i++) {
            if (s.charAt(i) == 'D') {
                int start = i;
                while (i < n - 1 && s.charAt(i) == 'D') {
                    i++;
                }
                reverse(result, start, i);
            }
        }
        
        return result;
    }
    
    private void reverse(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 484 (Find Permutation)?

This page provides optimized solutions for LeetCode problem 484 (Find Permutation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 484 (Find Permutation)?

The time complexity for LeetCode 484 (Find Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 484 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 484 in Java, C++, or Python.

Back to LeetCode Solutions