New Year Chaos

  • + 0 comments

    Can't shake the feeling that other solutions and explanations are just too complicated.

    Observations: - This is a que of people, normally always starts 1,2,3,4... - Since person can skip at most 2 positions, it means that if we look at que segment of size 3, we known that for arbirary position i only i, i+1 and i+2 can be there - So for initial segment [p1,p2,p3] at position p1 can only be 1 (the original), 2 (if it bribed) or 3 (if it bribed twice)

    So if normally the queue was supposed to start with [p1, p2, p3] = [1, 2, 3] , then by scanning the queue from left to right (via var x) and keeping track of p1, p2, p3 we can encounter the following cases

    1) x == p1 // x is at it's place and did not bribe anyone
    p1, p2, p3 = p2, p3, p3+1 // shift the window to the right

    2) x == p2 // x bribed once and skipepd 1 ahead bribes += 1 p2, p3 = p3, p3+1 // expected p1 is the same, p2 and p3 move to the right

    3) x == p3 // x bribed twice and skipped 2 ahead bribes += 2 p3 = p3+1 // we are still expecting the same p1 and p2, p3 moves to the right

    4) x is outside the window thus it's chaos

    Code in golang

    func minimumBribes(q []int32) {
    	// Write your code here
    	var bribes int32
    	// window of size 3
    	// starts by expecting the right order
    	var p1, p2, p3 int32 = 1, 2, 3
    
    	for _, x := range q {
    		switch {
    		// x = 1;  1 2 3 -> 2 3 4
    		case x == p1:
    			p1, p2, p3 = p2, p3, p3+1
    		// x = 2; 2 1 3 -> 1 3 4
    		case x == p2:
    			bribes += 1
    			p2, p3 = p3, p3+1
    		// x = 3; 3 1 2 -> 1 2 4
    		case x == p3:
    			bribes += 2
    			p3 = p3 + 1
    		default:
    			fmt.Println("Too chaotic")
    			return
    		}
    	}
    
    	fmt.Println(bribes)
    }