December 03, 2018

To Find the K th non repeated value in a String

/**
 * To Find the K th non repeated value in a String
 *
 * input hello 3
 * output o
 */
package com.sreejith.tutorials;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * @author KonzernTech
 *
 * Murali Krishanan
 *
 */
public class NonRepeatedElements {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);
String inputStr = "hello";
int k = 3;

Map<Character, Integer> varCountMap = new HashMap<>();
List<Character> nonRepeatChar = new ArrayList<>();

int len = inputStr.length();


for(int i=0;i<len;i++) {
Character thisChar = inputStr.charAt(i);
int count = 1;
if(varCountMap.get(thisChar)!=null) {
count = varCountMap.get(thisChar);
count = count + 1;
varCountMap.put(thisChar, count);
if(nonRepeatChar.contains(thisChar))
nonRepeatChar.remove(thisChar);

}else {
varCountMap.put(thisChar, count);
nonRepeatChar.add(thisChar);
}
}

System.out.println(nonRepeatChar.get(k-1));

}

}

Output

o

Description


 * To Find the Kth non repeated value in a String
 * 
 * input hello 3
 * output o

List nonRepeatChar = new ArrayList<>();

Why i used List here is add() and remove() works in the order

This question was asked from interview at https://infrrd.ai/

The time complexity of the program is n

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments