169. Majority Element Leetcode Solution
Majority Element Leetcode Problem :
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Majority Element Leetcode Solution :
Constraints :
- n == nums.length
- 1 <= n <= 5 * 10^4
- -10^9 <= nums[i] <= 10^9
Example 1:
- Input: nums = [2,2,1,1,1,2,2]
- Output: 2
Intuition :
The intuition behind this approach is that if an element occurs more than n/2 times in the array (where n is the size of the array), it will always occupy the middle position when the array is sorted. Therefore, we can sort the array and return the element at index n/2.
- The code begins by sorting the array nums in non-decreasing order using the sort function from the C++ Standard Library. This rearranges the elements such that identical elements are grouped together.
- Once the array is sorted, the majority element will always be present at index n/2, where n is the size of the array.
- This is because the majority element occurs more than n/2 times, and when the array is sorted, it will occupy the middle position.
- The code returns the element at index n/2 as the majority element.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: int majorityElement(vector& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); return nums[n/2]; } };
class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); int n = nums.length; return nums[n/2]; } }
class Solution: def majorityElement(self, nums: List[int]) -> int: nums.sort() n = len(nums) return nums[n//2]
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others