You are given a string s1
, a character c1
, and an integer k
. The task is to find the position of the k
th occurrence of the character c1
in the string s1
. If the k
th occurrence does not exist in the string, the program should output -1
.
Approach
The approach to solving this problem involves iterating through the string and counting occurrences of the character c1
. As you traverse the string, each time you encounter c1
, you increment a counter. When the counter reaches k
, you print the current index, which corresponds to the k
th occurrence of c1
. If you finish iterating through the string without the counter reaching k
, you print -1
to indicate that the k
th occurrence does not exist.
Complexity Analysis
-
Time Complexity: The time complexity is O(n), where
n
is the length of the strings1
. The string is traversed once to find thek
th occurrence. -
Space Complexity: The space complexity is O(1), as only a few integer variables are used regardless of the size of the input.