Welcome to Subscribe On Youtube

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

2451. Odd String Difference

  • Difficulty: Easy.
  • Related Topics: .
  • Similar Questions: Minimum Rounds to Complete All Tasks.

Problem

You are given an array of equal-length strings words. Assume that the length of each string is n.

Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.

  • For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1].

All the strings in words have the same difference integer array, except one. You should find that string.

Return** the string in words that has different difference integer array.**

  Example 1:

Input: words = ["adc","wzy","abc"]
Output: "abc"
Explanation: 
- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].
- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1].
- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1]. 
The odd array out is [1, 1], so we return the corresponding string, "abc".

Example 2:

Input: words = ["aaa","bob","ccc","ddd"]
Output: "bob"
Explanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].

  Constraints:

  • 3 <= words.length <= 100

  • n == words[i].length

  • 2 <= n <= 20

  • words[i] consists of lowercase English letters.

Solution (Java, C++, Python)

  • class Solution {
        public String oddString(String[] words) {
            Map<String, List<String>> cnt = new HashMap<>();
            for (var w : words) {
                List<String> d = new ArrayList<>();
                for (int i = 0; i < w.length() - 1; ++i) {
                    d.add(String.valueOf(w.charAt(i + 1) - w.charAt(i)));
                }
                cnt.computeIfAbsent(String.join(",", d), k -> new ArrayList<>()).add(w);
            }
            for (var v : cnt.values()) {
                if (v.size() == 1) {
                    return v.get(0);
                }
            }
            return "";
        }
    }
    
  • class Solution {
    public:
        string oddString(vector<string>& words) {
            unordered_map<string, vector<string>> cnt;
            for (auto& w : words) {
                string d;
                for (int i = 0; i < w.size() - 1; ++i) {
                    d += (char) (w[i + 1] - w[i]);
                    d += ',';
                }
                cnt[d].emplace_back(w);
            }
            for (auto& [_, v] : cnt) {
                if (v.size() == 1) {
                    return v[0];
                }
            }
            return "";
        }
    };
    
  • class Solution:
        def oddString(self, words: List[str]) -> str:
            cnt = defaultdict(list)
            for w in words:
                d = [str(ord(b) - ord(a)) for a, b in pairwise(w)]
                cnt[','.join(d)].append(w)
            return next(v[0] for v in cnt.values() if len(v) == 1)
    
    
  • func oddString(words []string) string {
    	cnt := map[string][]string{}
    	for _, w := range words {
    		d := make([]byte, len(w)-1)
    		for i := 0; i < len(w)-1; i++ {
    			d[i] = w[i+1] - w[i]
    		}
    		t := string(d)
    		cnt[t] = append(cnt[t], w)
    	}
    	for _, v := range cnt {
    		if len(v) == 1 {
    			return v[0]
    		}
    	}
    	return ""
    }
    
  • function oddString(words: string[]): string {
        const n = words[0].length;
        const map = new Map<string, [boolean, number]>();
        words.forEach((word, i) => {
            const diff: number[] = [];
            for (let j = 1; j < n; j++) {
                diff.push(word[j].charCodeAt(0) - word[j - 1].charCodeAt(0));
            }
            const k = diff.join();
            map.set(k, [!map.has(k), i]);
        });
        for (const [isOnly, i] of map.values()) {
            if (isOnly) {
                return words[i];
            }
        }
        return '';
    }
    
    
  • use std::collections::HashMap;
    impl Solution {
        pub fn odd_string(words: Vec<String>) -> String {
            let n = words[0].len();
            let mut map: HashMap<String, (bool, usize)> = HashMap::new();
            for (i, word) in words.iter().enumerate() {
                let mut k = String::new();
                for j in 1..n {
                    k.push_str(&(word.as_bytes()[j] - word.as_bytes()[j - 1]).to_string());
                    k.push(',');
                }
                let new_is_only = !map.contains_key(&k);
                map.insert(k, (new_is_only, i));
            }
            for (is_only, i) in map.values() {
                if *is_only {
                    return words[*i].clone();
                }
            }
            String::new()
        }
    }
    
    

Explain:

nope.

Complexity:

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

All Problems

All Solutions