Leetcode 2672: Number of Adjacent Elements With the Same Color

grid47
grid47
Exploring patterns and algorithms
Feb 13, 2024 6 min read

You are given an integer n, representing an array of n elements where all elements are initially set to 0 (uncolored). You are also given a 2D integer array queries, where each query specifies an index and a color. For each query, set the element at the specified index to the given color and then count the number of adjacent pairs of elements in the array that have the same color. Return an array answer where each element corresponds to the number of adjacent pairs with the same color after applying the corresponding query.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n` representing the size of the array and a 2D array `queries` where each query is a pair of integers: the index of the element to color and the color to set.
Example: Input: n = 5, queries = [[0,3],[1,2],[2,2],[3,1],[4,3]]
Constraints:
• 1 <= n <= 10^5
• 1 <= queries.length <= 10^5
• queries[i].length == 2
• 0 <= index_i <= n - 1
• 1 <= color_i <= 10^5
Output: The output should be an array `answer` of the same length as `queries`, where `answer[i]` is the number of adjacent pairs with the same color after applying the `i`-th query.
Example: Output: [0,1,2,2,3]
Constraints:
• Each element in the `answer` array represents the number of adjacent pairs with the same color after each query.
Goal: To efficiently count the number of adjacent pairs with the same color after applying each query.
Steps:
• Step 1: Initialize an array `colors` of size `n` where all elements are initially set to 0 (uncolored).
• Step 2: Initialize a variable `adj` to keep track of the current number of adjacent pairs with the same color.
• Step 3: For each query, update the color of the specified index and adjust the `adj` count based on the adjacent elements' colors.
• Step 4: After each query, store the current count of adjacent pairs with the same color in the result array `answer`.
Goal: The solution needs to efficiently handle the large inputs defined by the problem constraints.
Steps:
• Ensure that the solution runs in O(n) or O(n log n) time to handle the maximum input sizes within time limits.
Assumptions:
• The array `colors` is initially uncolored (all elements set to 0).
• Each query updates the color of exactly one element in the array.
Input: Input: n = 5, queries = [[0,3],[1,2],[2,2],[3,1],[4,3]]
Explanation: After the first query, the array becomes [3,0,0,0,0], with 0 adjacent pairs having the same color. After the second query, the array becomes [3,2,0,0,0], and there is 1 adjacent pair with the same color. After the third query, the array becomes [3,2,2,0,0], and there are 2 adjacent pairs with the same color, and so on.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus