Shortest Distance to a Character

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
LeetCode Problem - 821
class Solution {
public int[] shortestToChar(String s, char c) {
int n = s.length(); // Length of the input string
int[] answer = new int[n]; // Array to store the shortest distance to the character c
int prev = Integer.MIN_VALUE / 2; // Initialize previous occurrence index to a very small value
// First pass: from left to right
for (int i = 0; i < n; i++) {
// Update prev when the current character matches c
if (s.charAt(i) == c) {
prev = i;
}
// Calculate the distance from the current index to the last occurrence of c
answer[i] = i - prev;
}
prev = Integer.MAX_VALUE / 2; // Initialize previous occurrence index to a very large value
// Second pass: from right to left
for (int i = n - 1; i >= 0; i--) {
// Update prev when the current character matches c
if (s.charAt(i) == c) {
prev = i;
}
// Calculate the minimum distance from the current index to the nearest occurrence of c
answer[i] = Math.min(answer[i], prev - i);
}
return answer; // Return the array with shortest distances
}
}




