811. Subdomain Visit Count

interesting - use indexof is faster than split

TC: O(n*m)
SC: O(n*m worst) 
class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();
        for (String domain : cpdomains) {
            // String[] str = domain.split(" ");     
            // int count = Integer.parseInt(str[0]);
            // String url = str[1];
            
            int index = domain.indexOf(" ");
            int count = Integer.parseInt(domain.substring(0, index));
            String url = domain.substring(index+1, domain.length());

            int dotIndex = 0;
            while (url.length() != 0 && dotIndex != -1) {
                map.put(url, map.getOrDefault(url,0) + count);
                dotIndex = url.indexOf(".");
                url = url.substring(dotIndex + 1, url.length());
            }
        }
        List<String> result = new ArrayList<>();
        for (String key : map.keySet()) {
            result.add(map.get(key) + " " + key);
        }
        return result;
    }
}

/*


use hashMap

cpdomains count: n
dot count : m
TC: O(n*m)
SC: O(n*m worst) 

*/

Last updated