invalid Badge Records
Given a list of people who enter and exit, find the people who entered without their badge and who exited without their badge.
// badge_records = [
// ["Martha", "exit"],
// ["Paul", "enter"],
// ["Martha", "enter"],
// ["Martha", "exit"],
// ["Jennifer", "enter"],
// ["Paul", "enter"],
// ["Curtis", "enter"],
// ["Paul", "exit"],
// ["Martha", "enter"],
// ["Martha", "exit"],
// ["Jennifer", "exit"],
// ]
// Expected output: ["Paul", "Curtis"], ["Martha"]
https://leetcode.com/discuss/interview-question/982488/bettercom-phone-interview-badge-access
// 0 for exited, 1 for entered
public static List<List<String>> analyzeRecords(final String[][] badgeRecords) {
// 0 for exited, 1 for entered
Map<String, Integer> map = new HashMap<>();
final Set<String> invalidEnteriesSets = new HashSet<>();
final Set<String> invalidExitsSets = new HashSet<>();
for (String[] record : badgeRecords) {
String name = record[0];
String action = record[1];
if (action.equals("exit")) {
if (!map.containsKey(name) || map.get(name) != 1) {
invalidEnteriesSets.add(name);
} else {
map.put(name, 0);
}
}
if (action == "enter") {
if (!map.containsKey(name) || map.get(name) == 0) {
map.put(name, 1);
} else if (map.get(name) == 1) {
invalidExitsSets.add(name);
}
}
}
for (String name: map.keySet()) {
if (map.get(name) > 0) {
invalidExitsSets.add(name);
}
}
List<List<String>> result = new ArrayList<>();
List<String> invalidEnteriesList = new ArrayList<>(invalidEnteriesSets);
List<String> invalidExits = new ArrayList<>(invalidExitsSets);
result.add(invalidExits);
result.add(invalidEnteriesList);
return result;
}
public class Main {
// badge_records = [
// ["Martha", "exit"],
// ["Paul", "enter"],
// ["Martha", "enter"],
// ["Martha", "exit"],
// ["Jennifer", "enter"],
// ["Paul", "enter"],
// ["Curtis", "enter"],
// ["Paul", "exit"],
// ["Martha", "enter"],
// ["Martha", "exit"],
// ["Jennifer", "exit"],
// ]
// Expected output: ["Paul", "Curtis"], ["Martha"]
public List<List<String>> invalidBadgeRecord(String[][] badge)
{
List<List<String>> res = new ArrayList<>();
List<String> invalidExit = new ArrayList<>();
List<String> invalidEnter = new ArrayList<>();
// 0 is exit
// 1 is enter
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i< badges.length; i++)
{
String name = badges[i][0];
String action = badges[i][1];
if(action.equals("enter"))
{
// already entered before and now at exit status
if(!map.containsKey(name) || map.get(name) == 0)
{
map.put(name, 1);
}
else if(map.get(name) == 1)
{
if(!invalidExit.contains(name))
{
invalidExit.add(name);
}
}
}
if(action.euqals("exit"))
{
// valid exit
if(!map.containsKey(name) || map.get(name) == 0)
{
if(!invalidEnter.contains(name))
{
invalidEnter.add(name);
}
}
else
{
map.put(name, 0);
}
}
}
res.add(invalidEnter);
res.add(invalidExit);
return res;
}
}
Last updated