Program to find minimum jump needed to return from a folder to home in Python

PythonServer Side ProgrammingProgramming

Suppose we have a logs where we have path to enter into folders, there may be different symbols like −

  • "../" : Move to the parent folder from current one. (If we are at main folder, do not change location).

  • "./" : Remain in the current folder.

  • "x/" : Move to the child folder named x.

From the logs we have to find minimum number of operations needed to come back from last folder where we stop to the main folder.

So, if the input is like logs = ["Dir1/","Dir2/","../","Dir2/","Dir3/","./"], then the output will be 3

from the image we can see we have to step back thrice to reach home.

To solve this, we will follow these steps −

  • stk := a new list

  • for each item i in logs, do

    • if i is same as "../" and size of stk > 0, then

      • delete last element from stk

    • otherwise when i is not same as "./" and i is not same as "../", then

      • insert i at the end of stk

    • otherwise,

      • go for next iteration

  • return number of items in the stk

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(logs):
   stk = []
   for i in logs:
      if i == "../" and len(stk) > 0:
         stk.pop()
      elif i != "./" and i != "../":
         stk.append(i)
      else:
         continue
   return len(stk)

logs = ["Dir1/","Dir2/","../","Dir2/","Dir3/","./"]
print(solve(logs))

Input

["Dir1/","Dir2/","../","Dir2/","Dir3/","./"]

Output

3
raja
Updated on 17-May-2021 13:01:57

Advertisements