3834. Merge Adjacent Equal Elements Medium
1/**
2 * [3834] Merge Adjacent Equal Elements
3 *
4 * You are given an integer array nums.
5 * You must repeatedly apply the following merge operation until no more changes can be made:
6 *
7 * If any two adjacent elements are equal, choose the leftmost such adjacent pair in the current array and replace them with a single element equal to their sum.
8 *
9 * After each merge operation, the array size decreases by 1. Repeat the process on the updated array until no more changes can be made.
10 * Return the final array after all possible merge operations.
11 *
12 * <strong class="example">Example 1:
13 * <div class="example-block">
14 * Input: <span class="example-io">nums = [3,1,1,2]</span>
15 * Output: <span class="example-io">[3,4]</span>
16 * Explanation:
17 *
18 * The middle two elements are equal and merged into 1 + 1 = 2, resulting in [3, 2, 2].
19 * The last two elements are equal and merged into 2 + 2 = 4, resulting in [3, 4].
20 * No adjacent equal elements remain. Thus, the answer is [3, 4].
21 * </div>
22 * <strong class="example">Example 2:
23 * <div class="example-block">
24 * Input: <span class="example-io">nums = [2,2,4]</span>
25 * Output: <span class="example-io">[8]</span>
26 * Explanation:
27 *
28 * The first two elements are equal and merged into 2 + 2 = 4, resulting in [4, 4].
29 * The first two elements are equal and merged into 4 + 4 = 8, resulting in [8].
30 * </div>
31 * <strong class="example">Example 3:
32 * <div class="example-block">
33 * Input: <span class="example-io">nums = [3,7,5]</span>
34 * Output: <span class="example-io">[3,7,5]</span>
35 * Explanation:
36 * There are no adjacent equal elements in the array, so no operations are performed.
37 * </div>
38 *
39 * Constraints:
40 *
41 * 1 <= nums.length <= 10^5
42 * 1 <= nums[i] <= 10^5
43 *
44 */
45pub struct Solution {}
46
47// problem: https://leetcode.com/problems/merge-adjacent-equal-elements/
48// discuss: https://leetcode.com/problems/merge-adjacent-equal-elements/discuss/?currentPage=1&orderBy=most_votes&query=
49
50// submission codes start here
51
52impl Solution {
53 pub fn merge_adjacent(nums: Vec<i32>) -> Vec<i64> {
54
55 }
56}
57
58// submission codes end
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn test_3834() {
66 }
67}
68Back
© 2026 bowen.ge All Rights Reserved.