Find shortest distance in string

Last updated: November 12, 2025

Quick Overview

Given a string, write a function to find the shortest distance between two specified characters. The function should take the string and the two characters as input and return the shortest distance as an integer. If either character is not present in the string, return -1.

Zscaler
Coding & Algorithms
Software Engineer
Zscaler
November 12, 2025
Software Engineer
Technical Screen
Coding & Algorithms
Easy

33

4

2,247 solved


Given a string, write a function to find the shortest distance between two specified characters. The function should take the string and the two characters as input and return the shortest distance as an integer. If either character is not present in the string, return -1.

This coding problem is frequently asked during Technical Screen at Zscaler. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. Zscaler expects candidates to write production-quality code, not just solve the puzzle.

What the Interviewer Expects
  • Identify the correct data structure and algorithm for the problem
  • Write clean, bug-free code with proper variable naming
  • Analyze time and space complexity correctly
  • Handle basic edge cases (empty input, single element)
  • Communicate your thought process while coding
Key Topics to Cover
Time and space complexity analysis
Hash maps and frequency counting
Graph algorithms and traversal
Sorting and searching
Edge cases and input validation
Dynamic programming and memoization
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Can you solve this in a single pass?
  • What if the input doesn't fit in memory?
  • What happens if the input contains duplicates?
  • How would you test this solution thoroughly?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

To find the shortest distance between two specified characters in a given string, we can use a linear scanning approach. The problem can be effectively solved using a single traversal of the string wh...

Approach
  1. Initialize two variables, last_index_char1 and last_index_char2, to -1. These will store the last seen indices of the two characters.
  2. Initialize a variable min_distance to infinity to ke...

Submit Your Answer
Markdown supported

Related Questions