Minimum number of operations required to return to the main folder - GeeksforGeeks

17 Jul, 2021
Given an array of strings arr[] representing the changed folder operations(Unix-style) performed on the file system. Initially, the file system opens in the main folder. The task is to find the minimum count of operations of the following three types to return to the main folder:
“../”: Moves to the parent folder of the current folder. (If the current folder is the main folder, it remains in the same folder).
“./”: Remains in the same folder.
“F/”: Moves to the child folder named F.
Examples:
Input: arr[] = {“F1/”, “F2/”, “./”, “F3/”, “../”, “F31/”}Output: 3Explanation: arr[0] = “F1/”. Move to the child folder named F1. Therefore, the path of the current directory is /F1. arr[1] = “F2/”. Moves to the child’s folder, named F2. Therefore, the path of the current directory is /F1/F2 arr[2] = “./” . Remains in the current folder. Therefore, the path of the current directory is /F1/F2 arr[3] = “F3/”. Moves to the child’s folder, named F3. Therefore, the path of the current directory is /F1/F2/F3 arr[4] = “../”. Move to the parent folder of F3. Therefore, the path of the current directory is /F1/F2 arr[5] “F31/” . Move to the child’s folder, named F31. Therefore, the path of the current directory is /F1/F2/F31 Now, the “../” operation needs to be performed thrice to return to the main folder. Therefore, the required output is 3.
Input: arr[] = {“F1/”, “../”, “../”}Output: 0Explanation: arr[0] = “F1/”. Therefore, the path of the current directory is /F1. arr[1] = “../”. Therefore, the path of the current directory is / arr[2] = “../”. Therefore, the path of the current directory is / Since the current path of the directory is already in the main folder, no operations are required. Therefore, the required output is 0. 
Approach: The problem can be solved using Stack. Follow the steps below to solve the problem:
Initialize a variable, say cntOp to store the count of minimum operations required to go back to the main folder.
Create a Stack, say st to store the path of the current folder
Traverse the array and check the following conditions: If arr[i] == “../” then pop the top element of the stack.If arr[i] == “F/” then push the value of arr[i] on the top of the stack.
If arr[i] == “../” then pop the top element of the stack.
If arr[i] == “F/” then push the value of arr[i] on the top of the stack.
Finally, print the count of elements left onto the stack.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum number of// operations to go back to main folderint minOperations(vector<string>& arr,                               int N){    // Stores path of    // the current folder    stack<string> st;     for (int i = 0; i < N; i++) {               // If stack is not empty and        // the value of arr[i] is "../"        if (arr[i] == "../" &&                      !st.empty()) {                         // Pop top element of            // the stack                         st.pop();        }         // If the value of arr[i]        // is like "F/"        else if (arr[i] != "./") {                         // Push arr[i] on top element            // of the stack                          st.push(arr[i]);        }    }     // Return count of elements left    // into the stack    return st.size();} // Driver Codeint main(){    vector<string> arr        = { "F1/", "F2/", "./",          "F3/", "../", "F31/" };    int N = arr.size();    cout << minOperations(arr, N);}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find minimum number of// operations to go back to main folderstatic int minOperations(String []arr, int N){         // Stores path of    // the current folder    Stack<String> st = new Stack<>();     for(int i = 0; i < N; i++)    {                 // If stack is not empty and        // the value of arr[i] is "../"        if (arr[i] == "../" && !st.empty())        {                         // Pop top element of            // the stack                         st.pop();        }         // If the value of arr[i]        // is like "F/"        else if (arr[i] != "./")        {                         // Push arr[i] on top element            // of the stack                          st.push(arr[i]);        }    }     // Return count of elements left    // into the stack    return st.size();} // Driver Codepublic static void main(String args[]){    String []arr = { "F1/", "F2/", "./",                     "F3/", "../", "F31/" };                          int N = arr.length;         System.out.print(minOperations(arr, N));}} // This code is contributed by ipg2016107
# Python3 program to implement# the above approach # Function to find minimum number of# operations to go back to main folderdef minOperations(arr, N):         # Stores path of    # the current folder    st = []     for i in range(N):                 # If stack is not empty and        # the value of arr[i] is "../"        if (arr[i] == "../" and len(st) != 0):                         # Pop top element of            # the stack            st.pop(-1)         # If the value of arr[i]        # is like "F/"        elif (arr[i] != "./"):                         # Push arr[i] on top element            # of the stack            st.append(arr[i])     # Return count of elements left    # into the stack    return len(st) # Driver codeif __name__ == '__main__':         # Given array    arr = [ "F1/", "F2/", "./",            "F3/", "../", "F31/" ]     # Size of the array    N = len(arr)     # Function Call    print(minOperations(arr, N)) # This code is contributed by Shivam Singh
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find minimum// number of operations to// go back to main folderstatic int minOperations(String []arr,                         int N){     // Stores path of  // the current folder  Stack<String> st =        new Stack<String>();   for(int i = 0; i < N; i++)  {    // If stack is not empty    // and the value of arr[i]    // is "../"    if (arr[i] == "../" &&        st.Count != 0)    {      // Pop top element of      // the stack                   st.Pop();    }     // If the value of arr[i]    // is like "F/"    else if (arr[i] != "./")    {       // Push arr[i] on top      // element of the stack                    st.Push(arr[i]);    }  }   // Return count of elements  // left into the stack  return st.Count;} // Driver Codepublic static void Main(String []args){  String []arr = {"F1/", "F2/", "./",                  "F3/", "../", "F31/"};  int N = arr.Length;  Console.Write(minOperations(arr, N));}} // This code is contributed by gauravrajput1
<script>//Javascript  program to implement// the above approach // Function to find minimum number of// operations to go back to main folderfunction minOperations(arr, N){    // Stores path of    // the current folder    st = [];     for (var i = 0; i < N; i++) {               // If stack is not empty and        // the value of arr[i] is "../"        if (arr[i] == "../" && (st.length-1) !== 0) {                         // Pop top element of            // the stack                         st.pop();        }         // If the value of arr[i]        // is like "F/"        else if (arr[i] != "./") {                         // Push arr[i] on top element            // of the stack                          st.push(arr[i]);        }    }     // Return count of elements left    // into the stack    return st.length;} var arr = [ "F1/", "F2/", "./", "F3/", "../", "F31/" ];var N = arr.length;document.write( minOperations(arr, N)); // This code is contributed by SoumikMondal</script>
3
 
Time Complexity: O(N)Auxiliary Space: O(N)
SHIVAMSINGH67
ipg2016107
GauravRajput1
SoumikMondal
saurabh1990aror
cpp-stack
interview-preparation
Arrays
Stack
Strings
Arrays
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List vs Array
Program to find largest element in an array
Python | Using 2D arrays/lists the right way
Introduction to Arrays
Queue | Set 1 (Introduction and Array Implementation)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Stack | Set 2 (Infix to Postfix)
Inorder Tree Traversal without Recursion