
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 Sequence of Indices of Team Members in C++
Suppose we have an array A with n elements and a number k. There are n students in a class. The rating of ith student is A[i]. We have to form a team with k students such that rating of all team members are distinct. If not possible return "Impossible", otherwise return the sequence of indices.
So, if the input is like A = [15, 13, 15, 15, 12]; k = 3, then the output will be [1, 2, 5].
Steps
To solve this, we will follow these steps −
Define two large arrays app and ans and fill them with cnt := 0 n := size of A for initialize i := 1, when i <= n, update (increase i by 1), do: a := A[i - 1] if app[a] is zero, then: (increase app[a] by 1) increase cnt by 1; ans[cnt] := i if cnt >= k, then: for initialize i := 1, when i <= k, update (increase i by 1), do: print ans[i] Otherwise return "Impossible"
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A, int k) { int app[101] = { 0 }, ans[101] = { 0 }, cnt = 0; int n = A.size(); for (int i = 1; i <= n; i++) { int a = A[i - 1]; if (!app[a]) { app[a]++; ans[++cnt] = i; } } if (cnt >= k) { for (int i = 1; i <= k; i++) cout << ans[i] << ", "; } else cout << "Impossible"; } int main() { vector<int> A = { 15, 13, 15, 15, 12 }; int k = 3; solve(A, k); }
Input
{ 15, 13, 15, 15, 12 }, 3
Output
1, 2, 5,
Advertisements