Skip to content

Instantly share code, notes, and snippets.

@josephliccini
Last active November 20, 2021 12:08
Show Gist options
  • Save josephliccini/adbac3ce08e4448ebc3a to your computer and use it in GitHub Desktop.
Save josephliccini/adbac3ce08e4448ebc3a to your computer and use it in GitHub Desktop.
Palantir Coding Challenge Question
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Credit for Algorithm from top answer in:
* http://stackoverflow.com/questions/7116438/algorithms-question-flipping-columns
*
* This problem is given to interview candidates in the screening process
* for Palantir Technologies. I've seen it through several different
* candidates.
*
* Given an n*m Matrix of 'P' and 'T' characters, find the maximum number
* of completely 'P' rows, after k column flips.
*
* A column flip consists of taking one column in the matrix, and inverting
* it's values (i.e. all 'P' to 'T' and all 'T' to 'P')
*
* Here is an example matrix:
* PPT
* TPT
* TTT
*
* if k = 1, the optimal solution is:
* PPP
* TPP
* TTP
* and it should output 1.
*
* The number of all 'P' rows is 1, once the algorithm completes.
*
* The input for the above test case would be:
* 3 3
* PPT
* TPT
* TTT
* 1
*
* The output would be:
* 1
*
* @author Joseph Liccini
*
*/
public class PalantirCodingChallenge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] matrix = new char[n][m];
for (int i = 0; i < n; ++i)
matrix[i] = sc.next().toCharArray();
int k = sc.nextInt();
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < n; ++i) {
char[] row = matrix[i];
int count = 0;
for (char c: row)
if (c == 'T') ++count;
if (count == k || (k - count >= 0 && (k - count) % 2 != 0)) {
String key = new String(row);
if (map.containsKey(key))
map.put(key, map.get(key)+1);
else
map.put(key, 1);
}
}
int max = 0;
for (int value: map.values())
max = Math.max(value, max);
System.out.println(max);
sc.close();
}
}
@thorichelli
Copy link

I think;
(k - count) % 2 != 0) should be
(k - count) % 2 == 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment