Welcome to Subscribe On Youtube

3978. Unique Middle Element

Description

You are given an integer array nums of odd length n.

Return true if the middle element of nums appears exactly once in the array. Otherwise return false.

 

Example 1:

Input: nums = [1,2,3]

Output: true

Explanation:

The middle element of nums is 2, which appears exactly once.

Thus, the answer is true.

Example 2:

Input: nums = [1,2,2]

Output: false

Explanation:

The middle element of nums is 2, which appears twice.

Thus, the answer is false.

 

Constraints:

  • 1 <= n == nums.length <= 100
  • n is odd.
  • 1 <= nums[i] <= 100

Solutions

Solution 1: Simulation

We take the element at the middle index of the array and count how many times it appears. If the count is $1$, return $\textit{true}$; otherwise return $\textit{false}$.

The time complexity is $O(n)$, and the space complexity is $O(1)$, where $n$ is the length of the array $\textit{nums}$.

  • class Solution {
        public boolean isMiddleElementUnique(int[] nums) {
            int cnt = 0;
            for (int x : nums) {
                if (x == nums[nums.length / 2]) {
                    ++cnt;
                }
            }
            return cnt == 1;
        }
    }
    
  • class Solution {
    public:
        bool isMiddleElementUnique(vector<int>& nums) {
            int n = nums.size();
            int cnt = 0;
            for (int x : nums) {
                if (x == nums[n / 2]) {
                    ++cnt;
                }
            }
            return cnt == 1;
        }
    };
    
  • class Solution:
        def isMiddleElementUnique(self, nums: list[int]) -> bool:
            return nums.count(nums[len(nums) // 2]) == 1
    
    
  • func isMiddleElementUnique(nums []int) bool {
    	cnt := 0
    	for _, x := range nums {
    		if x == nums[len(nums)/2] {
    			cnt++
    		}
    	}
    	return cnt == 1
    }
    
    
  • function isMiddleElementUnique(nums: number[]): boolean {
        let cnt: number = 0;
        for (const x of nums) {
            if (x === nums[nums.length >> 1]) {
                ++cnt;
            }
        }
        return cnt === 1;
    }
    
    

All Problems

All Solutions