{"id":470,"date":"2025-06-29T20:32:47","date_gmt":"2025-06-29T15:02:47","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=470"},"modified":"2025-06-29T20:32:49","modified_gmt":"2025-06-29T15:02:49","slug":"majority-element-leetcode-169","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/","title":{"rendered":"Majority Element | Leetcode 169 | Explained in Python"},"content":{"rendered":"\n<p>The <strong>\u201cMajority Element\u201d<\/strong> problem (LeetCode #169) asks you to find the value that appears <strong>strictly more than \u230a n \/ 2 \u230b times<\/strong> in an integer array <code>nums<\/code> of length <code>n<\/code>. The input is guaranteed to contain such an element, so exactly <strong>one<\/strong> answer exists.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Example<\/strong><br>Input <code>[2, 2, 1, 1, 1, 2, 2]<\/code><br>Output <code>2<\/code> (because <code>2<\/code> occurs 4 &gt; 7\/2 = 3 times)<\/p>\n<\/blockquote>\n\n\n\n<p>Why it matters: detecting a clear majority is a classic voting-style task, leading to the elegant <strong>Boyer-Moore Voting Algorithm<\/strong> used in stream processing and data analytics.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/majority-element\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents\" id=\"ub_table-of-contents-0801c2e7-c5a7-4909-8d32-ca0f499915e2\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"true\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">hide<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column \">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#0-brute-force-solution-double-loop\" style=\"\">Brute Force Solution (Double Loop)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#4-dry-run-input-3-3-4-\" style=\"\">Dry Run (Input [3, 3, 4])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#7-better-solution-hash-map-frequency\" style=\"\">Better Solution (Hash Map Frequency)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#8-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#11-dry-run-input-2-2-1-\" style=\"\">Dry Run (Input [2, 2, 1])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#12-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#14-optimal-solution-boyer-moore-voting-algorithm\" style=\"\">Optimal Solution (Boyer-Moore Voting Algorithm)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#15-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#16-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#17-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#18-dry-run-input-2-2-1-1-1-2-2-\" style=\"\">Dry Run (Input [2, 2, 1, 1, 1, 2, 2])<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#19-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#20-conclusion\" style=\"\">Conclusion<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/majority-element-leetcode-169\/#21-final-thoughts\" style=\"\">Final Thoughts<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution-double-loop\">Brute Force Solution (Double Loop)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Compare every element against every other element, counting matches.<\/li>\n\n\n\n<li>The element whose count exceeds <code>n \/\/ 2<\/code> is the majority.<\/li>\n<\/ul>\n\n\n\n<p>Although straightforward, this is <strong>quadratic time<\/strong> and thus unsuitable for large arrays.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def majorityElement(self, nums: List[int]) -&gt; int:\n        n = len(nums)\n        for i in range(n):\n            cnt = 0\n            for j in range(n):\n                if nums[j] == nums[i]:\n                    cnt += 1          # increase count for each match\n            if cnt &gt; (n \/\/ 2):        # majority found\n                return nums[i]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">majorityElement<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            cnt = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[j] == nums[i]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    cnt += <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">          <\/span><span style=\"color: #6A9955\"># increase count for each match<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> cnt &gt; (n \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">):        <\/span><span style=\"color: #6A9955\"># majority found<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> nums[i]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Outer loop picks a potential candidate <code>nums[i]<\/code>.<\/li>\n\n\n\n<li>Inner loop counts its total occurrences.<\/li>\n\n\n\n<li>The first value whose count passes <code>\u230an\/2\u230b<\/code> is returned immediately.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run-input-3-3-4-\">Dry Run (Input <code>[3, 3, 4]<\/code>)<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><code>i = 0<\/code> (<code>nums[i] = 3<\/code>) \u2192 inner count = 2 \u2192 2 > 1 ? <strong>Yes<\/strong> \u2192 return <code>3<\/code>.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n\u00b2)<\/code> \u2013 nested scan across all pairs.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 constant extra memory.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Easy to code, but far too slow for anything beyond a few thousand elements.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-better-solution-hash-map-frequency\">Better Solution (Hash Map Frequency)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Maintain a <strong>hash map<\/strong> <code>num \u2192 frequency<\/code>.<\/li>\n\n\n\n<li>One linear pass builds the map; a second (or running check) locates the key whose frequency exceeds <code>n \/\/ 2<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def majorityElement(self, nums: List[int]) -&gt; int:\n        hash_map = dict()              # stores frequency of each number\n        n = len(nums)\n\n        # Build frequency table\n        for num in nums:\n            hash_map[num] = hash_map.get(num, 0) + 1\n\n        # Find the element with frequency &gt; n\/\/2\n        for k, v in hash_map.items():\n            if v &gt; n \/\/ 2:\n                return k\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">majorityElement<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        hash_map = <\/span><span style=\"color: #4EC9B0\">dict<\/span><span style=\"color: #D4D4D4\">()              <\/span><span style=\"color: #6A9955\"># stores frequency of each number<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Build frequency table<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> num <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> nums:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            hash_map[num] = hash_map.get(num, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">) + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Find the element with frequency &gt; n\/\/2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> k, v <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> hash_map.items():<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> v &gt; n \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> k<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Counting Pass:<\/strong> Updates the dictionary in <code>O(1)<\/code> average time per insertion.<\/li>\n\n\n\n<li><strong>Scanning Pass:<\/strong> Reads each <code>(key, value)<\/code> until it finds the majority.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run-input-2-2-1-\">Dry Run (Input <code>[2, 2, 1]<\/code>)<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Hash map after pass 1: <code>{2: 2, 1: 1}<\/code><\/li>\n\n\n\n<li>Pass 2 returns <code>2<\/code> because <code>2 > 3\/\/2<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n)<\/code> \u2013 linear over the array.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(k)<\/code> where <code>k<\/code> \u2264 <code>n<\/code> is the number of distinct elements.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Fast and clear, but extra hash-map storage may be unnecessary when we know a majority exists.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-optimal-solution-boyer-moore-voting-algorithm\">Optimal Solution (Boyer-Moore Voting Algorithm)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"15-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Idea:<\/strong> Pair off different elements so they \u201ccancel\u201d one another.<\/li>\n\n\n\n<li><strong>Candidate &amp; Count:<\/strong>\n<ul class=\"wp-block-list\">\n<li>When <code>count == 0<\/code>, adopt the current number as the new <code>candidate<\/code>.<\/li>\n\n\n\n<li>Increment <code>count<\/code> if the next number equals <code>candidate<\/code>, otherwise decrement.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Because the majority element appears more than all others combined, it <strong>survives<\/strong> these cancellations.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"16-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def majorityElement(self, nums: List[int]) -&gt; int:\n        candidate = nums[0]   # potential majority element\n        count = 0             # vote balance\n\n        for i in range(0, len(nums)):\n            if count == 0:            # no current leader\n                candidate = nums[i]\n                count = 1             # start fresh vote\n            elif nums[i] == candidate:\n                count += 1            # same as leader \u2192 gain vote\n            else:\n                count -= 1            # different \u2192 lose vote\n\n        return candidate              # guaranteed to be majority\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">majorityElement<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        candidate = nums[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">]   <\/span><span style=\"color: #6A9955\"># potential majority element<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># vote balance<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> count == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:            <\/span><span style=\"color: #6A9955\"># no current leader<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                candidate = nums[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count = <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">             <\/span><span style=\"color: #6A9955\"># start fresh vote<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> nums[i] == candidate:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count += <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># same as leader \u2192 gain vote<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                count -= <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># different \u2192 lose vote<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> candidate              <\/span><span style=\"color: #6A9955\"># guaranteed to be majority<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"17-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Vote Tally:<\/strong> Each matching number contributes +1; each different number contributes \u22121.<\/li>\n\n\n\n<li><strong>Reset Rule:<\/strong> When the balance hits 0, pick a new candidate (the old one is canceled out by equal opposition).<\/li>\n\n\n\n<li>Because the true majority owns more than half the votes, it cannot be fully canceled and emerges at the end.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"18-dry-run-input-2-2-1-1-1-2-2-\">Dry Run (Input <code>[2, 2, 1, 1, 1, 2, 2]<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Index<\/th><th>Num<\/th><th>Candidate<\/th><th>Count<\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>2<\/td><td>2<\/td><td>1<\/td><\/tr><tr><td>1<\/td><td>2<\/td><td>2<\/td><td>2<\/td><\/tr><tr><td>2<\/td><td>1<\/td><td>2<\/td><td>1<\/td><\/tr><tr><td>3<\/td><td>1<\/td><td>2<\/td><td>0<\/td><\/tr><tr><td>4<\/td><td>1<\/td><td>1<\/td><td>1<\/td><\/tr><tr><td>5<\/td><td>2<\/td><td>1<\/td><td>0<\/td><\/tr><tr><td>6<\/td><td>2<\/td><td>2<\/td><td>1<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Loop ends with <code>candidate = 2<\/code>, which is indeed the majority.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"19-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n)<\/code> \u2013 single pass.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 just two variables.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"20-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The Boyer-Moore algorithm is the perfect fit:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>One pass<\/strong><\/li>\n\n\n\n<li><strong>Constant space<\/strong><\/li>\n\n\n\n<li><strong>Mathematically guaranteed<\/strong> if a majority exists<\/li>\n<\/ul>\n\n\n\n<p>It\u2019s the go-to answer for interviewers whenever you\u2019re asked to find a majority element in linear time.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"21-final-thoughts\">Final Thoughts<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Solution<\/th><th>Time<\/th><th>Space<\/th><th>Key Idea<\/th><\/tr><\/thead><tbody><tr><td><strong>Brute<\/strong><\/td><td><code>O(n\u00b2)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Count each element via nested loops<\/td><\/tr><tr><td><strong>Better<\/strong><\/td><td><code>O(n)<\/code><\/td><td><code>O(k)<\/code><\/td><td>Hash-map frequency table<\/td><\/tr><tr><td><strong>Optimal<\/strong><\/td><td><code>O(n)<\/code><\/td><td><code>O(1)<\/code><\/td><td>Boyer-Moore voting<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Understanding how <strong>pairwise cancellation<\/strong> reduces memory from a hash map to two variables is a valuable lesson you can reuse in many stream-processing and majority-vote problems. Happy coding!<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The \u201cMajority Element\u201d problem (LeetCode #169) asks you to find the value that appears strictly more than \u230a n \/ 2 \u230b times in an integer array nums of length n. The input is guaranteed to contain such an element, so exactly one answer exists. ExampleInput [2, 2, 1, 1, 1, 2, 2]Output 2 (because<\/p>\n","protected":false},"author":1,"featured_media":472,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[3,6],"tags":[7,19],"class_list":{"0":"post-470","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-array","10":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/majority-element-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/470","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=470"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/470\/revisions"}],"predecessor-version":[{"id":474,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/470\/revisions\/474"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/472"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=470"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=470"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=470"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}