Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/2399.html

2399. Check Distances Between Same Letters

  • Difficulty: Easy.
  • Related Topics: Array, Hash Table, String.
  • Similar Questions: Two Sum, Shortest Distance to a Character.

Problem

You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.

Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, … , 'z' -> 25).

In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.

Return true** if s is a well-spaced string, otherwise return **false.

  Example 1:

Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
Explanation:
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.
- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.
- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.
Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.
Return true because s is a well-spaced string.

Example 2:

Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: false
Explanation:
- 'a' appears at indices 0 and 1 so there are zero letters between them.
Because distance[0] = 1, s is not a well-spaced string.

  Constraints:

  • 2 <= s.length <= 52

  • s consists only of lowercase English letters.

  • Each letter appears in s exactly twice.

  • distance.length == 26

  • 0 <= distance[i] <= 50

Solution (Java, C++, Python)

  • class Solution {
        public boolean checkDistances(String s, int[] distance) {
            
            boolean valid = true;
            
            HashMap<Character,Integer> map = new HashMap<>();
            int n = s.length();
            
            // System.out.println('c'-'a');
            
            for(int i = 0 ; i < n ; i++){
                
                char c = s.charAt(i);
                if(map.containsKey(c)){
                    int value = i - map.get(c) - 1;
                    if(value != distance[c-'a'])return false;
                }else{
                    map.put(c,i);
                }
            }
            
            return valid;
        }
    }
    
    ############
    
    class Solution {
        public boolean checkDistances(String s, int[] distance) {
            int[] d = new int[26];
            for (int i = 0; i < s.length(); ++i) {
                int j = s.charAt(i) - 'a';
                if (d[j] > 0 && i - d[j] != distance[j]) {
                    return false;
                }
                d[j] = i + 1;
            }
            return true;
        }
    }
    
  • class Solution:
        def checkDistances(self, s: str, distance: List[int]) -> bool:
            d = [0] * 26
            for i, c in enumerate(s):
                j = ord(c) - ord("a")
                if d[j] and i - d[j] != distance[j]:
                    return False
                d[j] = i + 1
            return True
    
    ############
    
    # 2399. Check Distances Between Same Letters
    # https://leetcode.com/problems/check-distances-between-same-letters/
    
    class Solution:
        def checkDistances(self, s: str, distance: List[int]) -> bool:
            dist = {}
            
            for i, x in enumerate(s):
                if x not in dist:
                    dist[x] = i
                else:
                    k = ord(x) - ord("a")
                    
                    if distance[k] != i - dist[x] - 1:
                        return False
                
            return True
    
    
  • class Solution {
    public:
        bool checkDistances(string s, vector<int>& distance) {
            vector<int> d(26);
            for (int i = 0; i < s.size(); ++i) {
                int j = s[i] - 'a';
                if (d[j] && i - d[j] != distance[j]) {
                    return false;
                }
                d[j] = i + 1;
            }
            return true;
        }
    };
    
  • func checkDistances(s string, distance []int) bool {
    	d := make([]int, 26)
    	for i, c := range s {
    		j := c - 'a'
    		if d[j] > 0 && i-d[j] != distance[j] {
    			return false
    		}
    		d[j] = i + 1
    	}
    	return true
    }
    
  • function checkDistances(s: string, distance: number[]): boolean {
        const n = s.length;
        const d = new Array(26).fill(0);
        for (let i = 0; i < n; i++) {
            const j = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
            if (d[j] > 0 && i - d[j] !== distance[j]) {
                return false;
            }
            d[j] = i + 1;
        }
        return true;
    }
    
    
  • impl Solution {
        pub fn check_distances(s: String, distance: Vec<i32>) -> bool {
            let n = s.len();
            let s = s.as_bytes();
            let mut d = [0; 26];
            for i in 0..n {
                let j = (s[i] - b'a') as usize;
                let i = i as i32;
                if d[j] > 0 && i - d[j] != distance[j] {
                    return false;
                }
                d[j] = i + 1;
            }
            true
        }
    }
    
    

Explain:

nope.

Complexity:

  • Time complexity : O(n).
  • Space complexity : O(n).

All Problems

All Solutions