- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 67 lines of Java from the credited upstream file 1538.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * 3 * 4 * interface ArrayReader {5 * 6 * 7 * 8 * 9 * 10 * 11 * public int query(int a, int b, int c, int d);12 *13 * 14 * public int length();15 * };16 */17 18class Solution {19 public int guessMajority(ArrayReader reader) {20 final int n = reader.length();21 final int query0123 = reader.query(0, 1, 2, 3);22 final int query1234 = reader.query(1, 2, 3, 4);23 24 int zeros = 1;25 26 int nonZeros = 0;27 28 int indexNot0 = -1;29 30 31 for (int i = 1; i <= 3; ++i) {32 List<Integer> abcd = getABCD(i);33 if (reader.query(abcd.get(0), abcd.get(1), abcd.get(2), abcd.get(3)) == query1234) {34 ++zeros;35 } else {36 ++nonZeros;37 indexNot0 = i;38 }39 }40 41 42 for (int i = 4; i < n; ++i)43 if (reader.query(1, 2, 3, i) == query0123) {44 ++zeros;45 } else {46 ++nonZeros;47 indexNot0 = i;48 }49 50 if (zeros == nonZeros)51 return -1;52 if (zeros > nonZeros)53 return 0;54 return indexNot0;55 }56 57 58 private List<Integer> getABCD(int i) {59 List<Integer> abcd = new ArrayList<>(List.of(0));60 for (int j = 1; j <= 3; ++j)61 if (j != i)62 abcd.add(j);63 abcd.add(4);64 return abcd;65 }66}67