This is a standard question which has been answered many a times in several sites but in this version there are additional constraints:
I've seen this problem on InterviewBit and I guess I've the solution right, captured the logic I followed to find the 'k'th smallest element in array below..
int getSmallest(const int* A, int nSize){
int nSmallestElemIndex = -1;
int i;
for(i=0; i < nSize; i++){
if (-1 == nSmallestElemIndex){
nSmallestElemIndex = i;
continue;
}
if (A[i] < A[nSmallestElemIndex]){
nSmallestElemIndex = i;
}
}
return nSmallestElemIndex;
}
int nextBig(const int* A, int nSize, int nCurrentSmallest){
int nNextBig = -1;
int i;
for(i=0; i < nSize; i++){
if (i == nCurrentSmallest || A[i] < A[nCurrentSmallest]){
continue;
}
if (A[i] == A[nCurrentSmallest] &&
i <= nCurrentSmallest){
continue;
}
if (nNextBig == -1){
nNextBig = i;
continue;
}
if (A[i] >= A[nCurrentSmallest] && A[i] < A[nNextBig]){
nNextBig = i;
}
}
return nNextBig;
}
int kthsmallest(const int* A, int n1, int B) {
int nSmallestElem = getSmallest(A, n1);
int nCount = 1;
int nRes = nSmallestElem;
while(nCount < B){
nRes = nextBig(A, n1, nRes);
nCount++;
}
return nRes;
}
I executed and validated it for the test cases on my machine but it's not accepted at Interviewbit.
I'll be glad if the solution passes your validation. Let me know your comments.