Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 31 · Two Pointers

Next Permutation

LeetCode 31 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Find the pivot, swap with the next-larger tail value, sort the tail.

ಮಧ್ಯಮArrayTwo Pointers
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Next Permutation (LeetCode 31) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Pointers ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Find the last place where the sequence still increases — that's the pivot just before it. Swap the pivot with the smallest larger value to its right, then put the tail in ascending order to make the smallest possible arrangement after the pivot.

Approach

  1. 1

    Scan for the last index where nums[i] > nums[i−1].

  2. 2

    If there is none, the array is the largest permutation — reverse it.

  3. 3

    Among the tail, find the smallest value still larger than the pivot and swap.

  4. 4

    Sort the tail ascending.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Pivot + swap + sort tailPythonO(n log n) time
class Solution:
    def nextPermutation(self, nums):
        n = len(nums)
        lastIndex = -1
        i = 1
        while i < n:
            if nums[i] > nums[i - 1]:
                lastIndex = i
            i += 1
        # 3,2,1 -> fully descending
        if lastIndex == -1:
            for i in range(n // 2):
                nums[i], nums[n - i - 1] = nums[n - i - 1], nums[i]
            return
        # special case 1,3,2
        index = lastIndex
        for i in range(lastIndex, n):
            if nums[i] < nums[lastIndex] and nums[i] > nums[lastIndex - 1]:
                index = i
        nums[index], nums[lastIndex - 1] = nums[lastIndex - 1], nums[index]
        chopped = sorted(nums[lastIndex:])
        del nums[lastIndex:]
        nums.extend(chopped)
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Next Permutation — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Next Permutation ಹಿಂದಿನ intuition ಏನು?

Find the last place where the sequence still increases — that's the pivot just before it. Swap the pivot with the smallest larger value to its right, then put the tail in ascending order to make the smallest possible arrangement after the pivot.

Next Permutation (LeetCode 31) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Scan for the last index where nums[i] > nums[i−1]. 2. If there is none, the array is the largest permutation — reverse it. 3. Among the tail, find the smallest value still larger than the pivot and swap. 4. Sort the tail ascending.

Next Permutation ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log n) here (O(n) if the tail is reversed instead of sorted). Space: O(1). (Accepted approach: Pivot + swap + sort tail.)

Next Permutation ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

The tail is descending, so reversing it is enough — sorting works but is slower.