Problem Understanding
The problem requires us to determine the first position of a specified character in a given string. If the character exists in the string, we need to print its index (0-based). If the character does not exist in the string, we should print -1
.
Approach
To solve the problem, we use a simple linear search approach. We iterate through each character in the string, comparing it to the target character. If we find a match, we immediately record the index of the first occurrence and break out of the loop. If no match is found after checking all characters, we output -1
to indicate that the character is not present in the string. This method ensures we efficiently find the first occurrence with a time complexity of O(n), where n is the length of the string.
Complexity Analysis
-
Time Complexity: The time complexity of this solution is O(n), where
n
is the length of the input string. In the worst case, the algorithm might need to check each character of the string to determine if thesearchChar
is present. -
Space Complexity: The space complexity is O(1), as the solution only uses a few extra variables (
position
and loop counters) regardless of the input size.
Edge Cases
- If the input string is empty, the algorithm will immediately output
-1
, as there are no characters to search through. - If the
searchChar
is the first character in the string, the algorithm will quickly find it and output0
. - If the
searchChar
does not exist in the string, the algorithm will correctly output-1
.