Open In App

Python – Mid occurrence of K in string

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, the task is to write a Python program to extract the mid occurrence of a character. 

Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘e’

Output : 10

Explanation : 7 occurrences of e. The 4th occurrence [mid] is at 10th index.

Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘g’

Output : 8

Explanation : 3 occurrences of g. The 2nd occurrence [mid] is at 8th index.

Method #1 : Using enumerate() + list comprehension

In this, we perform the task of getting all occurrences using list comprehension and enumerate gets all indices. Post that the middle element of the list is printed to get mid occurrence of a character.

Python3




# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using find() + max() + slice
 
# initializing string
test_str = "geeksforgeeks is best for all geeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 'e'
 
# getting all the indices of K
indices = [idx for idx, ele in enumerate(test_str) if ele == K]
 
# getting mid index
res = indices[len(indices) // 2]
 
# printing result
print("Mid occurrence of K : " + str(res))


Output:

The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10

Time Complexity: O(n)

Space Complexity: O(n)

Method #2 : Using finditer() + list comprehension + regex

In this, the character is found using regex and finditer(). The mid occurrence is the mid element of the indices list.

Python3




# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using finditer() + list comprehension + regex
import re
 
# initializing string
test_str = "geeksforgeeks is best for all geeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 'e'
 
# getting all the indices of K
# using regex
indices = [ele.start() for ele in re.finditer(K, test_str)]
 
# getting mid index
res = indices[len(indices) // 2]
 
# printing result
print("Mid occurrence of K : " + str(res))


Output:

The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10

Time Complexity: O(n)

Auxiliary Space: O(n)

Approach#3: Using a loop to count the occurrences of K

This approach first counts the total number of occurrences of the character K in the given string. Then, it calculates the mid index by dividing the count by 2 and taking the ceiling value. Finally, it iterates over the string again and counts the occurrences of K until it reaches the mid index, and returns the index of that mid occurrence. If there is no mid occurrence, it returns -1.

Algorithm

1. Initialize a count variable to 0.
2. Traverse the string character by character and increment the count variable by 1 if the character is equal to K.
3. Compute the mid occurrence of K by dividing the count variable by 2 and rounding up.
4. Traverse the string again and keep track of the number of occurrences of K seen so far.
5. If the number of occurrences seen so far is equal to the mid occurrence, return the current index.
6. Return -1 if the mid occurrence is not found.

Python3




import math
 
def mid_occurrence(str_, K):
    count = 0
    for i in range(len(str_)):
        if str_[i] == K:
            count += 1
    mid = math.ceil(count / 2)
    count = 0
    for i in range(len(str_)):
        if str_[i] == K:
            count += 1
            if count == mid:
                return i
    return -1
str_ = "geeksforgeeks is best for all geeks"
K='e'
print(mid_occurrence(str_, K))


Output

10

Time complexity: O(n), where n is the length of the string.

Auxiliary Space: O(1).

Approach#4:  Using the lambda function 

In this approach, the lambda function takes two arguments test_str and K, which are the string and the character to be searched for, respectively.

The lambda function uses a generator expression [ele.start() for ele in re.finditer(K, test_str)] to find all the indices of the character K in the string test_str using regex. 

The lambda function then calculates the middle index of the indices list indices using (lambda indices: indices[len(indices) // 2] if indices else -1)(…). If the indices list is not empty, it returns the middle index, otherwise, it returns -1.

Below is the code for the above approach: 

Python3




import re
 
mid_occurrence = lambda test_str, K: (lambda indices:
    indices[len(indices) // 2] if indices else -1
)([ele.start() for ele in re.finditer(K, test_str)])
 
# initializing string
test_str = "geeksforgeeks is best for all geeks"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 'e'
 
# getting mid index
res = mid_occurrence(test_str, K)
 
# printing result
print("Mid occurrence of K : " + str(res))


Output

The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10

Time complexity: O(n)
Auxiliary Space: O(m), where m is the number of occurrences of the character K in the string test_str

METHOD 5:

APPROACH: Using for loop and counter variable.

The given problem can be solved using a simple iteration over the string while keeping track of the count of the character K. Once the count reaches the mid occurrence of K in the string, the index of that occurrence can be returned.

ALGORITHM:

1.Initialize a counter variable to 0.
2.Iterate over the string using a for loop and an index variable.
3.If the character at the current index is equal to the given character K, increment the counter variable.
4.Check if the counter is equal to the mid occurrence of K in the string, which can be calculated by dividing the total count of K by 2 and adding 1. 5.If the condition is true, return the current index.
6.If the loop completes without finding the mid occurrence of K, return -1.

Python3




test_str = "geeksforgeeks is best for all geeks"
K = 'e'
count = 0
for i in range(len(test_str)):
    if test_str[i] == K:
        count += 1
        if count == (test_str.count(K) // 2 + 1):
            print(i)
            break


Output

10

Time Complexity:

The time complexity of this approach is O(n), where n is the length of the input string. This is because we are iterating over the string once.

Auxiliary Space:

The space complexity of this approach is O(1), because we are only using a constant amount of extra space for the counter variable and the loop variable.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads