[LeetCode] 2460. Apply Operations to an Array (Python)

2025. 3. 1. 15:53·알고리즘/LeetCode

 

 

난이도: Easy

Problem Description


You are given a 0-indexed array nums of size n consisting of non-negative integers.

 

You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:

  • If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.

After performing all the operations, shift all the 0's to the end of the array.

  • For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].

Return the resulting array.

 

Note that the operations are applied sequentially, not all at once.

 

Problem Example


Example 1:

Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].

Example 2:

Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.

 

Constraints


  • 2 <= nums.length <= 2000
  • 0 <= nums[i] <= 1000

 

✏️ Solution


class Solution:
    def applyOperations(self, nums: List[int]) -> List[int]:
        n = len(nums)
        answer = []

        for i in range(n):
            if i+1 < n and nums[i] == nums[i+1]:
                nums[i] *= 2
                nums[i+1] = 0
            
            if nums[i] != 0:
                answer.append(nums[i])
        
        for _ in range(n-len(answer)):
            answer.append(0)

        return answer

 

문제에서 주어진대로 `nums`의 요소들을 확인하여 `nums[i] == nums[i+1]`이면 `nums[i]`에 2를 곱하고 `nums[i+1]`은 0으로 만들어 주었다.

 

이후 현재 `nums[i]`가 0이 아니면 `answer` 리스트에 추가해주었다.

 

이렇게 하면 모든 요소를 확인했을 때, `answer`에는 0이 아닌 요소들만 들어가 있다.

 

예를 들어 `nums`가 [1,0,2,0,0,1]이라고 한다면 `answer`에는 [1,2,1]로 채워진다.

 

이제 nums의 길이 - answer의 길이 만큼 0을 answer에 채워주면 된다.

 

마지막에는 answer를 return 하고 정답을 맞을 수 있었다.

 

⚙️ Runtime & Memory


 

 


문제: 2460. Apply Operations to an Array

 

깃허브: github

 

algorithmPractice/LeetCode/2551-apply-operations-to-an-array at main · laewonJeong/algorithmPractice

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

github.com

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 2161. Partition Array According to Given Pivot (Python)  (0) 2025.03.03
[LeetCode] 2570. Merge Two 2D Arrays by Summing Values (Python)  (0) 2025.03.02
[LeetCode] 1092. Shortest Common Supersequence (Python)  (0) 2025.02.28
[LeetCode] 873. Length of Longest Fibonacci Subsequence (Python)  (0) 2025.02.27
[LeetCode] 1749. Maximum Absolute Sum of Any Subarray (Python)  (0) 2025.02.26
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 2161. Partition Array According to Given Pivot (Python)
  • [LeetCode] 2570. Merge Two 2D Arrays by Summing Values (Python)
  • [LeetCode] 1092. Shortest Common Supersequence (Python)
  • [LeetCode] 873. Length of Longest Fibonacci Subsequence (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    dfs
    쿠버네티스
    leetcode
    DP
    아파치 스파크
    String
    리트코드
    티스토리챌린지
    누적합
    아파치 하둡
    heapq
    BFS
    그래프
    알고리즘
    백트래킹
    Apache Spark
    코딩테스트
    Python
    프로그래머스
    문자열
    Kubernetes
    도커
    오블완
    분산처리
    docker
    programmers
    우선순위큐
    이진탐색
    파이썬
    분산
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2460. Apply Operations to an Array (Python)
상단으로

티스토리툴바