[C++, Python, Java] Single Pass, Easy and Readable Code with Comments
Key Idea\nIt\'s not difficult to realize that when k is greater than the size of the array, then the max number, say M, in the array has to be the winner.\nThis
**Key Idea**\nIt\'s not difficult to realize that when `k` is greater than the size of the array, then the max number, say `M`, in the array has to be the winner.\nThis is because, the moment we reach the `M`, the winner is not going to change. It will always be `M`.\n\nSo if you find an answer before reaching `M`, immediately return. Otherwise, `M` is going to be the answer.\n\nReading C++ code should give the detailed idea. \n\n**Thanks**\nThanks for reading. If you find this helpful, please upvote so that -\n1.  It encourages me to write more and share solutions on Leetcode and on my blog/website, if I have an easy, intuitive approach to solve the problem.\n2.  Other learners get to see the post near the top\n\n\n**C++**\n```\nclass Solution {\npublic:\n    int getWinner(vector<int>& arr, int k) {\n        unordered_map<int, int> matchesWon;\n        int n = arr.size();\n        int currentMax = arr[0];  // Assume first element as max, but don\'t increment the "matchesWon" count.\n        for (int i=1; i<n; i++) {\n            currentMax = max(currentMax, arr[i]); // Match.\n            matchesWon[currentMax]++;  // Increment the winner.\n            if (matchesWon[currentMax] >= k) { // Check the matches won so far.\n                return currentMax;\n            }\n        }\n\t\t// Didn\'t find the overall winner yet? Then the max element in the array will never lose, so ultimately\n\t\t// that number will be the winner.\n        return currentMax;\n    }\n};\n```\n\n**Python**\n```\nclass Solution(object):\n    def getWinner(self, arr, k):\n        d = dict()\n        n = len(arr)\n        mx = arr[0]\n        for i in range(1, n):\n            mx = max(mx, arr[i])\n            d[mx] = d[mx] + 1 if mx in d.keys() else 1\n            if d[mx] >= k:\n                return mx\n        return mx\n```\n\n**Java**\n```\npublic int getWinner(int[] arr, int k) {\n        Map<Integer, Integer> matchesWon = new HashMap<>();\n        int n = arr.length;\n        int currentMax = arr[0];  // Assume first element as max, but don\'t increment the "matchesWon" count.\n        for (int i = 1; i < n; i++) {\n            currentMax = Math.max(currentMax, arr[i]); // Match.\n            int count = matchesWon.getOrDefault(currentMax, 0);\n            matchesWon.put(currentMax, ++count);  // Increment the winner.\n            if (matchesWon.get(currentMax) >= k) { // Check the matches won so far.\n                return currentMax;\n            }\n        }\n        // Didn\'t find the overall winner yet? Then the max element in the array will never lose, so ultimately\n        // that number will be the winner.\n        return currentMax;\n    }\n```\n
[]