Unique Middle Element Problem
#3978
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3978.
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 <= 100nis odd.1 <= nums[i] <= 100
Solution
Approach: Simulation
The array has odd length n, so the middle element is at index n / 2 (integer division). Count how many elements are equal to it. The middle element counts itself, so the answer is true exactly when the count is 1.
Complexity: O(n) time and O(1) space, where n is the length of nums.
class Solution:
def isMiddleElementUnique(self, nums: List[int]) -> bool:
return nums.count(nums[len(nums) // 2]) == 1