Number of paths in a grid (backtracking) in JavaScript












0












$begingroup$


I was asked to solve this problem today for one of my interviews. I
would like to ask for feedback and a code review since I was rusty on the backtracking problem.




You’re testing a new driverless car that is located at the Southwest
(bottom-left) corner of an n×n grid. The car is supposed to get to the
opposite, Northeast (top-right), corner of the grid. Given n, the size
of the grid’s axes, write a function numOfPathsToDest that returns the
number of the possible paths the driverless car can take.



For convenience, let’s represent every square in the grid as a pair
(i,j). The first coordinate in the pair denotes the east-to-west axis,
and the second coordinate denotes the south-to-north axis. The initial
state of the car is (0,0), and the destination is (n-1,n-1).



The car must abide by the following two rules: it cannot cross the
diagonal border. In other words, in every step the position (i,j)
needs to maintain i >= j. See the illustration above for n = 5. In
every step, it may go one square North (up), or one square East
(right), but not both. E.g. if the car is at (3,1), it may go to (3,2)
or (4,1).



Explain the correctness of your function, and analyze its time and
space complexities.



Example:



input: n = 4



output: 5 # since there are five possibilities:
# “EEENNN”, “EENENN”, “ENEENN”, “ENENEN”, “EENNEN”,
# where the 'E' character stands for moving one step
# East, and the 'N' character stands for moving one step
# North (so, for instance, the path sequence “EEENNN”
# stands for the following steps that the car took:
# East, East, East, North, Nor




Time Complexity: the function still calculates every square south-east to the diagonal, leaving the time complexity to be $O(n^2)$.



Space Complexity: the space complexity is reduced to $O(n)$ since we are memoizing only the last two rows.



function numOfPathsToDest(n) {

//num_paths(i,j)=num_paths(i,j-1)+num_paths(i-1,j)
let num_paths = ;

for (let i =0; i <n; i++){
num_paths[i] = [1];
}

for (let i = 1; i < n; i++){
for (let j = 0; j <= i; j++){
let top = num_paths[i-1][j] || 0;
let left = num_paths[i][j-1] || 0;
num_paths[i][j] = left + top;
}
}

return num_paths[n-1][n-1];

}









share|improve this question











$endgroup$

















    0












    $begingroup$


    I was asked to solve this problem today for one of my interviews. I
    would like to ask for feedback and a code review since I was rusty on the backtracking problem.




    You’re testing a new driverless car that is located at the Southwest
    (bottom-left) corner of an n×n grid. The car is supposed to get to the
    opposite, Northeast (top-right), corner of the grid. Given n, the size
    of the grid’s axes, write a function numOfPathsToDest that returns the
    number of the possible paths the driverless car can take.



    For convenience, let’s represent every square in the grid as a pair
    (i,j). The first coordinate in the pair denotes the east-to-west axis,
    and the second coordinate denotes the south-to-north axis. The initial
    state of the car is (0,0), and the destination is (n-1,n-1).



    The car must abide by the following two rules: it cannot cross the
    diagonal border. In other words, in every step the position (i,j)
    needs to maintain i >= j. See the illustration above for n = 5. In
    every step, it may go one square North (up), or one square East
    (right), but not both. E.g. if the car is at (3,1), it may go to (3,2)
    or (4,1).



    Explain the correctness of your function, and analyze its time and
    space complexities.



    Example:



    input: n = 4



    output: 5 # since there are five possibilities:
    # “EEENNN”, “EENENN”, “ENEENN”, “ENENEN”, “EENNEN”,
    # where the 'E' character stands for moving one step
    # East, and the 'N' character stands for moving one step
    # North (so, for instance, the path sequence “EEENNN”
    # stands for the following steps that the car took:
    # East, East, East, North, Nor




    Time Complexity: the function still calculates every square south-east to the diagonal, leaving the time complexity to be $O(n^2)$.



    Space Complexity: the space complexity is reduced to $O(n)$ since we are memoizing only the last two rows.



    function numOfPathsToDest(n) {

    //num_paths(i,j)=num_paths(i,j-1)+num_paths(i-1,j)
    let num_paths = ;

    for (let i =0; i <n; i++){
    num_paths[i] = [1];
    }

    for (let i = 1; i < n; i++){
    for (let j = 0; j <= i; j++){
    let top = num_paths[i-1][j] || 0;
    let left = num_paths[i][j-1] || 0;
    num_paths[i][j] = left + top;
    }
    }

    return num_paths[n-1][n-1];

    }









    share|improve this question











    $endgroup$















      0












      0








      0





      $begingroup$


      I was asked to solve this problem today for one of my interviews. I
      would like to ask for feedback and a code review since I was rusty on the backtracking problem.




      You’re testing a new driverless car that is located at the Southwest
      (bottom-left) corner of an n×n grid. The car is supposed to get to the
      opposite, Northeast (top-right), corner of the grid. Given n, the size
      of the grid’s axes, write a function numOfPathsToDest that returns the
      number of the possible paths the driverless car can take.



      For convenience, let’s represent every square in the grid as a pair
      (i,j). The first coordinate in the pair denotes the east-to-west axis,
      and the second coordinate denotes the south-to-north axis. The initial
      state of the car is (0,0), and the destination is (n-1,n-1).



      The car must abide by the following two rules: it cannot cross the
      diagonal border. In other words, in every step the position (i,j)
      needs to maintain i >= j. See the illustration above for n = 5. In
      every step, it may go one square North (up), or one square East
      (right), but not both. E.g. if the car is at (3,1), it may go to (3,2)
      or (4,1).



      Explain the correctness of your function, and analyze its time and
      space complexities.



      Example:



      input: n = 4



      output: 5 # since there are five possibilities:
      # “EEENNN”, “EENENN”, “ENEENN”, “ENENEN”, “EENNEN”,
      # where the 'E' character stands for moving one step
      # East, and the 'N' character stands for moving one step
      # North (so, for instance, the path sequence “EEENNN”
      # stands for the following steps that the car took:
      # East, East, East, North, Nor




      Time Complexity: the function still calculates every square south-east to the diagonal, leaving the time complexity to be $O(n^2)$.



      Space Complexity: the space complexity is reduced to $O(n)$ since we are memoizing only the last two rows.



      function numOfPathsToDest(n) {

      //num_paths(i,j)=num_paths(i,j-1)+num_paths(i-1,j)
      let num_paths = ;

      for (let i =0; i <n; i++){
      num_paths[i] = [1];
      }

      for (let i = 1; i < n; i++){
      for (let j = 0; j <= i; j++){
      let top = num_paths[i-1][j] || 0;
      let left = num_paths[i][j-1] || 0;
      num_paths[i][j] = left + top;
      }
      }

      return num_paths[n-1][n-1];

      }









      share|improve this question











      $endgroup$




      I was asked to solve this problem today for one of my interviews. I
      would like to ask for feedback and a code review since I was rusty on the backtracking problem.




      You’re testing a new driverless car that is located at the Southwest
      (bottom-left) corner of an n×n grid. The car is supposed to get to the
      opposite, Northeast (top-right), corner of the grid. Given n, the size
      of the grid’s axes, write a function numOfPathsToDest that returns the
      number of the possible paths the driverless car can take.



      For convenience, let’s represent every square in the grid as a pair
      (i,j). The first coordinate in the pair denotes the east-to-west axis,
      and the second coordinate denotes the south-to-north axis. The initial
      state of the car is (0,0), and the destination is (n-1,n-1).



      The car must abide by the following two rules: it cannot cross the
      diagonal border. In other words, in every step the position (i,j)
      needs to maintain i >= j. See the illustration above for n = 5. In
      every step, it may go one square North (up), or one square East
      (right), but not both. E.g. if the car is at (3,1), it may go to (3,2)
      or (4,1).



      Explain the correctness of your function, and analyze its time and
      space complexities.



      Example:



      input: n = 4



      output: 5 # since there are five possibilities:
      # “EEENNN”, “EENENN”, “ENEENN”, “ENENEN”, “EENNEN”,
      # where the 'E' character stands for moving one step
      # East, and the 'N' character stands for moving one step
      # North (so, for instance, the path sequence “EEENNN”
      # stands for the following steps that the car took:
      # East, East, East, North, Nor




      Time Complexity: the function still calculates every square south-east to the diagonal, leaving the time complexity to be $O(n^2)$.



      Space Complexity: the space complexity is reduced to $O(n)$ since we are memoizing only the last two rows.



      function numOfPathsToDest(n) {

      //num_paths(i,j)=num_paths(i,j-1)+num_paths(i-1,j)
      let num_paths = ;

      for (let i =0; i <n; i++){
      num_paths[i] = [1];
      }

      for (let i = 1; i < n; i++){
      for (let j = 0; j <= i; j++){
      let top = num_paths[i-1][j] || 0;
      let left = num_paths[i][j-1] || 0;
      num_paths[i][j] = left + top;
      }
      }

      return num_paths[n-1][n-1];

      }






      javascript interview-questions






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 18 mins ago









      Jamal

      30.3k11117227




      30.3k11117227










      asked 1 hour ago









      NinjaGNinjaG

      787528




      787528






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212951%2fnumber-of-paths-in-a-grid-backtracking-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212951%2fnumber-of-paths-in-a-grid-backtracking-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'