Facebook director of photography puzzle overflow
Anonymous User
8644

Hi All,

Trying to solve this puzzle:
image

using System.Collections.Generic;
class Solution {
  // sliding window counting P and B on the left and the right side of A
  // .PBAAP.B
  //  11^01
  //   10^10
  public long getArtisticPhotographCount(int N, string C, int X, int Y) {
   
    long ct = 0;
    // left part of sliding window
	var left = new Dictionary<char, int>() {
      { 'B', 0 },
      { 'P', 0 } 
    };
	
    // right part of sliding window
    var right = new Dictionary<char, int>() {
      { 'B', 0 },
      { 'P', 0 } 
    };
    
	// find an A
    var i = 0;
    while(i < N && C[i] != 'A') i++;
    if (i == N) return 0;
    
	// initialize left part of sliding window
    for(var j = X; j <= Y && i-j >=0; j++)
    {      
      if (left.ContainsKey(C[i-j])) left[C[i-j]]++;
    }
    
	// initialize right part of sliding window
    for(var j = X; j <= Y && i+j < N; j++)
    {      
      if (right.ContainsKey(C[i+j])) right[C[i+j]]++;
    }

    // slide the window
    while(i < N)
    {
      if (C[i] == 'A')
      {
	    // compute number of artistic photographs within the window
        ct += left['P']*right['B']+left['B']*right['P'];
      }
      
	  // left part remove and append character as we slide the window
      if (i - Y >= 0 && left.ContainsKey(C[i - Y])) left[C[i - Y]]--;
      if (i - X + 1 >= 0 && left.ContainsKey(C[i - X + 1])) left[C[i - X + 1]]++;
      
	  // right part remove and append character as we slide the window
      if (i + X < N && right.ContainsKey(C[i + X])) right[C[i + X]]--;
      if (i + Y + 1 < N && right.ContainsKey(C[i + Y + 1])) right[C[i + Y + 1]]++;           
    
      i++;
    }
      
    return ct;
  } 
}

It fails two test cases, from my testing i figured that the issue is overflow of ct counter. Any suggestions or alternative solutions?

Thanks!

Comments (56)