Java O(1) solution with explanation


  • 0
    P
    class Solution {
        public int flipLights(int n, int m) {
            // for the 4 operations(labeled 1-4, also suppose the original condition is 0):
            // 1 + 2 -> 3
            // 1 + 3 -> 2
            // 2 + 3 -> 1
            // So if n <= 2 and m == 1, the conditions are 1,2,3
            // if m >= 2, the conditions are 0,1,2,3
            // if n > 2, we need to also count condition 4
            // if m == 1, the conditions are 1,2,3,4
            // if m == 2, the conditions are 0,1,2,3,1+4,2+4,3+4
            // if m > 2, the conditions are 0,1,2,3,0+4,1+4,2+4,3+4
            if (n == 0) return 0;
            if (m == 0) return 1;
            if (n == 1) return 2;
            if (n <= 2) {
                if (m == 1) return 3;
                else return 4;
            }
            else if (m == 1) return 4;
            else if (m == 2) return 7;
            else return 8;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.