Given an array of strings, the duty is to print “Sure” if it comprises a string that may be a prefix of one other string in any other case, print “No”.
Examples:
Enter: arr[] = {“rud”, “rudra”, “rahi”}
Output: Sure
Rationalization: arr[0] = “rud” is a prefix of arr[1] = “rudra”, that’s why “Sure” is the output.Enter: arr[] = {“baj”, “mnc”, “rahi”, “banjo”}
Output: NoEnter: arr[] = {“bahe”, “baj”, “jabf”, “bahej”}
Output: Sure
Method: To resolve the issue observe the under thought:
The method mainly requires us to match one string to a different, such that checking whether or not one comprises prefix of one other, with the assistance of discover methodology which returns the primary place the place there’s a prefix match, and in case of prefix it will undoubtedly be zero.
Steps to observe to implement the method:
- The “hasPrefix” operate takes an array of strings “arr” and its measurement “n” as enter.
- It then iterates via every string within the array, and for every string, it checks if it’s a prefix of another string within the array utilizing the “discover” methodology of the “string” class. Whether it is, the operate instantly returns “true”.
- If no string is discovered to be a prefix of one other string, the operate returns “false”.
- The principle operate creates an instance string array, calls the “hasPrefix” operate, and prints “Sure” if the operate returns “true”, and “No” in any other case.
Under is the implementation of the above method:
C++
|
Java
|
C#
|
Time Complexity: O(n^2 * m), the place n is the size of the enter array and m is the utmost size of a string within the array. It’s because the code makes use of nested loops to match each pair of strings within the array, and for every pair, it makes use of the discover methodology to test if one string is a prefix of the opposite. The discover methodology has a time complexity of O(m).
Auxiliary House: O(1), because it solely makes use of a set quantity of reminiscence to retailer the enter array and some loop variables. The area used doesn’t rely on the dimensions of the enter.