
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Winner of Unique Bidding Game in C++
Suppose we have an array A with n elements. There are n participants, the i-th participant chose the number A[i]. The winner of the bidding game is such a participant that the number he chose is unique and is minimal. We have to find the index of the participant who won the game. If not possible, return -1.
Problem Category
Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can. This problem we can solve by some basic logics or brute-force approach. Follow the following contents to understand the approach better.
So, if the input of our problem is like A = [2, 3, 2, 4, 2], then the output will be 1, because the participant who has chosen 3 can win the game.
Steps
To solve this, we will follow these steps −
Define one map cnt, and another map pos, both for integer type key and integer type value n := size of A for initialize i := 0, when i < n, update (increase i by 1), do: x := A[i] increase cnt[x + 1] by 1 pos[x + 1] = i ans := -1 for each key-value pair it in cnt, do if value of it is same as 1, then: ans := pos[key of it] Come out from the loop return ans
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ map<int, int> cnt, pos; int n = A.size(); for (int i = 0; i < n; i++){ int x = A[i]; cnt[x + 1]++; pos[x + 1] = i; } int ans = -1; for (auto it : cnt){ if (it.second == 1){ ans = pos[it.first]; break; } } return ans; } int main(){ vector<int> A = { 2, 3, 2, 4, 2 }; cout << solve(A) << endl; }
Input
{ 2, 3, 2, 4, 2 }
Output
1