889201. Search a Character in a String

Easy

Search a Character in a String

Slug: search-a-character-in-a-string Difficulty: Easy Id: 889201

Summary

This problem requires you to write an algorithm that searches for a specific character in a given string. The goal is to find the first occurrence of the target character in the string and return its index.

Detailed Explanation

To solve this problem, we can use a simple iterative approach. We iterate through each character in the string and check if it matches the target character. If we find a match, we return the current index as the result.

Here's the step-by-step breakdown of the solution:

  1. Initialize an index variable to 0.
  2. Iterate through each character c in the input string.
  3. For each character, check if it matches the target character using a conditional statement (e.g., if (c == targetCharacter)).
  4. If the current character matches the target character, return the current index as the result.
  5. If we reach the end of the string without finding the target character, return -1 to indicate that the character was not found.

Here's an ASCII art diagram illustrating the algorithm:

  +---------------+
  |  Input String  |
  +---------------+
           |
           v
  +---------------+
  |  Iterate through  |
  |  each character    |
  +---------------+
           |
           v
  +---------------+
  |  Check if current  |
  |  character matches|
  |  target character  |
  +---------------+
           |
           v
  +---------------+
  |  Return index if  |
  |  match found, -1   |
  |  otherwise        |
  +---------------+

Time complexity: O(n), where n is the length of the input string. Space complexity: O(1), as we only use a few extra variables to store the index and the target character.

Optimized Solutions

Java

View on GeeksforGeeks
public int searchCharacter(String s, char c) {
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == c) {
            return i;
        }
    }
    return -1;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.