mah-shamim / leet-code-in-php

Php-based LeetCode algorithm problem solutions, regularly updated.
GNU General Public License v3.0
14 stars 6 forks source link

1598. Crawler Log Folder #19

Closed mah-shamim closed 4 months ago

mah-shamim commented 4 months ago

The Leetcode file system keeps a log each time some user performs a change folder operation.

The operations are described below:

You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.

The file system starts in the main folder, then the operations in logs are performed.

Return the minimum number of operations needed to go back to the main folder after the change folder operations.

Example 1:

Example 2:

Example 3:

Constraints:

mah-shamim commented 4 months ago
  1. Initialize a counter to keep track of the current depth of the folder hierarchy.
  2. Iterate through each operation in the logs array.
  3. For each operation:
    • If the operation is "../", decrement the depth counter if it's greater than zero.
    • If the operation is "./", do nothing.
    • If the operation is a folder change (i.e., it ends with "/" but isn't "./" or "../"), increment the depth counter.
  4. Return the value of the depth counter, which represents the minimum number of "../" operations required to return to the main folder.

Here's the PHP implementation of this logic:

<?php
function minOperations($logs) {
    $depth = 0;

    foreach ($logs as $log) {
        if ($log == "../") {
            if ($depth > 0) {
                $depth--;
            }
        } elseif ($log != "./") {
            $depth++;
        }
    }

    return $depth;
}

// Test cases
$logs1 = ["d1/", "d2/", "../", "d21/", "./"];
$logs2 = ["d1/", "d2/", "./", "d3/", "../", "d31/"];
$logs3 = ["d1/", "../", "../", "../"];

echo minOperations($logs1); // Output: 2
echo "\n";
echo minOperations($logs2); // Output: 3
echo "\n";
echo minOperations($logs3); // Output: 0
?>

Explanation: