Program for longest common directory path
Last Updated :
28 Dec, 2023
Given n directory paths, we need to write a program to find longest common directory path.
Examples:
Input : 3
"/home/User/Desktop/gfg/test"
"/home/User/Desktop/gfg/file"
"/home/User/Desktop/geeks/folders"
Output : Longest Common Path is /home/User/Desktop!
Input : 4
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
Output : Longest Common Path is /home/User/Desktop/gfg!
In the function LongestCommonPath() there are two main variables used which are "CommonCharacters" for storing the length of common characters and "CommonString" for storing the longest string of paths so that we get our longest common path.
CommonCharacter variable gets updated in each iteration depending upon the length of common path appearing in the input paths.
Lastly, we get the length of common path string after the iteration. Then, we get our common path by the substring till the separator '/' as if we don't do this then we get the longest common string among the paths, which should not be our result .
Below is the implementation of the above approach .
CPP
// CPP program for longest common path
#include <bits/stdc++.h>
using namespace std;
string LongestCommonPath(const vector<string>& input_directory,
char separator)
{
vector<string>::const_iterator iter;
// stores the length of common characters
// and initialized with the length of
// first string .
int CommonCharacters = input_directory[0].length();
// stores the common string and initialized
// with the first string .
string CommonString = input_directory[0];
for (iter = input_directory.begin() + 1;
iter != input_directory.end(); iter++) {
// finding the two pointers through the mismatch()
// function which is 'mismatch at first string' and
// 'mismatch at the other string '
pair<string::const_iterator, string::const_iterator> p =
mismatch(CommonString.begin(),
CommonString.end(), iter->begin());
// As the first mismatch string pointer points to the mismatch
// present in the "CommonString" so "( p.first-CommonString.begin())"
// determines the common characters in each iteration .
if ((p.first - CommonString.begin()) < CommonCharacters) {
// If the expression is smaller than commonCharacters
// then we will update the commonCharacters because
// this states that common path is smaller than the
// string commonCharacters we have evaluated till .
CommonCharacters = p.first - CommonString.begin();
}
// Updating CommonString variable
// so that in this maximum length
// string is stored .
if (*iter > CommonString)
CommonString = *iter;
}
// In 'found' variable we store the index of '/' in
// the length of common characters in CommonString
int found;
for (int i = CommonCharacters; i >= 0; --i) {
if (CommonString[i] == '/') {
found = i;
break;
}
}
// The substring from index 0 to index of
// separator is the longest common substring
return CommonString.substr(0, found);
}
int main()
{
int n = 4;
string input_directory[4] = {
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
};
vector<string> input(input_directory,
input_directory + n);
cout << "Longest Common Path is "
<< LongestCommonPath(input, '/') << "!\n";
return 0;
}
Java
import java.util.*;
public class GFG {
public static String LongestCommonPath(final List<String> input_directory,
final char separator)
{
// stores the length of common characters
// and initialized with the length of
// first string .
int CommonCharacters = input_directory.get(0).length();
// stores the common string and initialized
// with the first string .
String CommonString = input_directory.get(0);
for (int i = 1; i < input_directory.size(); i++) {
String iter = input_directory.get(i);
int n = Math.min(CommonString.length(), iter.length());
int j = 0;
while (j < n && CommonString.charAt(j) == iter.charAt(j)) {
j++;
}
if (j < CommonCharacters) {
CommonCharacters = j;
}
if (iter.compareTo(CommonString) > 0) {
CommonString = iter;
}
}
// In 'found' variable we store the index of '/' in
// the length of common characters in CommonString
int found = -1;
for (int i = CommonCharacters; i >= 0; --i) {
if (CommonString.charAt(i) == separator) {
found = i;
break;
}
}
// The substring from index 0 to index of
// separator is the longest common substring
return CommonString.substring(0, found);
}
public static void main(String[] args) {
String[] input_directory = {
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
};
List<String> input = new ArrayList<>(Arrays.asList(input_directory));
System.out.println("Longest Common Path is " +
LongestCommonPath(input, '/') + "!");
}
}
Python3
# Python program for the above approach
from typing import List
def LongestCommonPath(input_directory: List[str], separator: str) -> str:
# stores the length of common characters
# and initialized with the length of
# first string.
CommonCharacters = len(input_directory[0])
# stores the common string and initialized
# with the first string.
CommonString = input_directory[0]
for i in range(1, len(input_directory)):
# finding the two pointers through the mismatch()
# function which is 'mismatch at first string' and
# 'mismatch at the other string '
p = mismatch(CommonString, input_directory[i])
# As the first mismatch string pointer points to the mismatch
# present in the "CommonString" so "( p[0])"
# determines the common characters in each iteration.
if p[0] < CommonCharacters:
# If the expression is smaller than CommonCharacters
# then we will update the CommonCharacters because
# this states that common path is smaller than the
# string CommonCharacters we have evaluated till.
CommonCharacters = p[0]
# Updating CommonString variable
# so that in this maximum length
# string is stored.
if len(input_directory[i]) > len(CommonString):
CommonString = input_directory[i]
# In 'found' variable we store the index of separator in
# the length of common characters in CommonString
found = CommonString.rfind(separator, 0, CommonCharacters)
# The substring from index 0 to index of separator
# is the longest common substring
return CommonString[:found]
def mismatch(s1, s2):
n = min(len(s1), len(s2))
for i in range(n):
if s1[i] != s2[i]:
return (i, s1[i], s2[i])
if len(s1) != len(s2):
return (n, "", "")
return (-1, "", "")
if __name__ == '__main__':
n = 4
input_directory = [
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
]
print("Longest Common Path is", LongestCommonPath(input_directory, '/'), "!")
# This code is contributed by codebraxnzt
C#
using System;
using System.Collections.Generic;
class GFG {
public static string
LongestCommonPath(List<string> input_directory,
char separator)
{
// Initialize the length of common characters and
// the common string with the first string.
int CommonCharacters = input_directory[0].Length;
string CommonString = input_directory[0];
// Iterate through the list of input strings.
for (int i = 1; i < input_directory.Count; i++) {
string iter = input_directory[i];
// Find the minimum length between the current
// CommonString and the current input string.
int n = Math.Min(CommonString.Length,
iter.Length);
int j = 0;
// Find the number of common characters between
// the two strings.
while (j < n && CommonString[j] == iter[j]) {
j++;
}
// Update CommonCharacters with the minimum
// number of common characters.
if (j < CommonCharacters) {
CommonCharacters = j;
}
// Update CommonString with the
// lexicographically larger string.
if (string.Compare(iter, CommonString) > 0) {
CommonString = iter;
}
}
// Find the last separator character within the
// first CommonCharacters characters.
int found = -1;
for (int i = CommonCharacters; i >= 0; i--) {
if (CommonString[i] == separator) {
found = i;
break;
}
}
// Return the longest common path by taking a
// substring from the beginning to the found
// separator.
return CommonString.Substring(0, found);
}
public static void Main(string[] args)
{
// List of input strings
string[] input_directory
= { "/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders" };
List<string> input
= new List<string>(input_directory);
// Print the longest common path
Console.WriteLine("Longest Common Path is "
+ LongestCommonPath(input, '/')
+ "!");
}
}
JavaScript
// Javascript program for the above approach
function LongestCommonPath(input_directory, separator)
{
// stores the length of common characters
// and initialized with the length of
// first string.
let CommonCharacters = input_directory[0].length;
// stores the common string and initialized
// with the first string.
let CommonString = input_directory[0];
for (let i = 1; i < input_directory.length; i++)
{
// finding the two pointers through the mismatch()
// function which is 'mismatch at first string' and
// 'mismatch at the other string '
let p = mismatch(CommonString, input_directory[i]);
// As the first mismatch string pointer points to the mismatch
// present in the "CommonString" so "( p[0])"
// determines the common characters in each iteration.
if (p[0] < CommonCharacters)
{
// If the expression is smaller than CommonCharacters
// then we will update the CommonCharacters because
// this states that common path is smaller than the
// string CommonCharacters we have evaluated till.
CommonCharacters = p[0];
}
// Updating CommonString variable
// so that in this maximum length
// string is stored.
if (input_directory[i] > CommonString) {
CommonString = input_directory[i];
}
}
// In 'found' variable we store the index of separator in
// the length of common characters in CommonString
let found = CommonString.lastIndexOf(separator, CommonCharacters);
// The substring from index 0 to index of separator
// is the longest common substring
return CommonString.substring(0, found);
}
function mismatch(s1, s2) {
let n = Math.min(s1.length, s2.length);
for (let i = 0; i < n; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return [i, s1.charAt(i), s2.charAt(i)];
}
}
if (s1.length != s2.length) {
return [n, "", ""];
}
return [-1, "", ""];
}
let input_directory = [
"/home/User/Desktop/gfg/test",
"/home/User/Desktop/gfg/file",
"/home/User/Desktop/gfg/folders",
"/home/User/Desktop/gfg/folders"
];
console.log("Longest Common Path is", LongestCommonPath(input_directory, '/'), "!");
OutputLongest Common Path is /home/User/Desktop/gfg!
Similar Reads
Longest path in a directed Acyclic graph | Dynamic Programming Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1->3->2->4 Input: N = 5, M = 8 Output: 3 Simple
8 min read
Find Longest Common Subpath Given an integer n and m friends and a 2D integer array paths[][] where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a con
5 min read
Longest Path in a Directed Acyclic Graph Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph. The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesnât have optimal substr
15+ min read
Find minimum shift for longest common prefix You are given two strings str1 and str2 of the same length. In a single shift, you can rotate one string (str2) by 1 element such that its 1st element becomes the last and the second one becomes the first like "abcd" will change to "bcda" after the one-shift operation. You have to find the minimum s
7 min read
Longest Common Prefix using Linked List Given a set of strings, find the longest common prefix. Examples: Input : {âgeeksforgeeksâ, âgeeksâ, âgeekâ, âgeezerâ} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using
14 min read