알고리즘/LeetCode

[LeetCode] 2780. Minimum Index of a Valid Split (Python)

Laewon Jeong 2025. 3. 27. 14:25

 

 

난이도: Medium

Problem Description


An element x of an integer array arr of length m is dominant if more than half the elements of arr have a value of x.

 

You are given a 0-indexed integer array nums of length n with one dominant element.

 

You can split nums at an index i into two arrays nums[0, ..., i] and nums[i + 1, ..., n - 1], but the split is only valid if:

  • 0 <= i < n - 1
  • nums[0, ..., i], and nums[i + 1, ..., n - 1] have the same dominant element.

Here, nums[i, ..., j] denotes the subarray of nums starting at index i and ending at index j, both ends being inclusive. Particularly, if j < i then nums[i, ..., j] denotes an empty subarray.

 

Return the minimum index of a valid split. If no valid split exists, return -1.

 

Problem Example


Example 1:

Input: nums = [1,2,2,2]
Output: 2
Explanation: We can split the array at index 2 to obtain arrays [1,2,2] and [2]. 
In array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 > 3. 
In array [2], element 2 is dominant since it occurs once in the array and 1 * 2 > 1.
Both [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. 
It can be shown that index 2 is the minimum index of a valid split.

Example 2:

Input: nums = [2,1,3,1,1,1,7,1,2,1]
Output: 4
Explanation: We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1].
In array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.
In array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.
Both [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split.
It can be shown that index 4 is the minimum index of a valid split.

Example 3:

Input: nums = [3,3,3,3,7,2,2]
Output: -1
Explanation: It can be shown that there is no valid split.

 

Constraints


  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • nums has exactly one dominant element.

 

✏️ Solution


class Solution:
    def minimumIndex(self, nums: List[int]) -> int:
        n = len(nums)
        nums_counter = Counter(nums)
        cnt, max_num = max((v, k) for k, v in nums_counter.items())

        left_cnt = 0
        right_cnt = cnt
        for i, num in enumerate(nums):
            if num == max_num:
                if (left_cnt+1) * 2 > i + 1 and (right_cnt-1) * 2 > n-i-1:
                    return i
                else:
                    left_cnt += 1
                    right_cnt -= 1

        return -1

nums에서 제일 많이 등장하는 숫자를 가지고 문제를 해결할 수 있었다.

 

분할했을 때 왼쪽과 오른쪽의 제일 많이 등장하는 숫자의 갯수를 세었다.

 

처음에는 왼쪽의 카운트를 0, 오른쪽의 카운트를 제일 많이 등장하는 숫자의 갯수로 저장했다.

 

이제 각 nums의 요소를 제일 많이 등장하는 숫자와 비교하여 같다면 left_cnt += 1, right -= 1 연산을 진행했다.

 

이 때, left_cnt * 2의 값이 왼쪽 부분의 길이보다 크고 right_cnt * 2의 값이 오른쪽 부분의 길이보다 크면 바로 현재 index를 반환하면 된다.

 

만약 모든 요소를 확인했을 때, 조건을 만족하지 않는다면 마지막에 -1을 반환하고 정답을 맞을 수 있었다.

 


 

처음에는 다음과 같이 문제를 해결했다.

class Solution:
    def minimumIndex(self, nums: List[int]) -> int:
        n = len(nums)
        nums_counter = Counter(nums)
        left_counter = Counter()

        for i, num in enumerate(nums):
            left_counter[num] += 1
            nums_counter[num] -= 1

            if left_counter[num] * 2 > i + 1 and nums_counter[num] * 2 > n-i-1:
                return i

        return -1

근데 이는 Runtime이 하위 15%로 좋지 않게 나와서 어떻게 고칠 수 있을까 생각하다가 제일 많이 등장하는 숫자를 기준으로 하면 굳이 Counter()를 2개를 만들 필요가 없을 것 같았다.

 

따라서, 위 코드를 위위 코드로 수정하여 최종 답안을 제출했다.

 

 

⚙️ Runtime & Memory


최종 제출 결과

 

 

첫번째 제출 결과

 

 


문제: 2780. Minimum Index of a Valid Split

 

깃허브: github

 

algorithmPractice/LeetCode/2888-minimum-index-of-a-valid-split at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com