Press "Enter" to skip to content

Posts tagged as “hash”

花花酱 LeetCode 1316. Distinct Echo Substrings

Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself.

Example 1:

Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Example 2:

Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".

Constraints:

  • 1 <= text.length <= 2000
  • text has only lowercase English letters.

Solution 1: Brute Force + HashSet

Try all possible substrings

Time complexity: O(n^3)
Space complexity: O(n^2)

C++

花花酱 LeetCode 652. Find Duplicate Subtrees

652. Find Duplicate SubtreesMedium730151FavoriteShare

Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with same node values.

Example 1:

The following are two duplicate subtrees:

        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4

2
/
4

and

4

Therefore, you need to return above trees’ root in the form of a list.

Solution 1: Serialization

Time complexity: O(n^2)
Space complexity: O(n^2)

C++

Solution 2: int id for each unique subtree

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

C++

花花酱 LeetCode 690. Employee Importance

https://leetcode.com/problems/employee-importance/description/

Problem:

ou are given a data structure of employee information, which includes the employee’s unique id, his importance value and his direct subordinates’ id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

Example 1:

Note:

  1. One employee has at most one direct leader and may have several subordinates.
  2. The maximum number of employees won’t exceed 2000.

Idea:

BFS / DFS

Time complexity: O(n)

Space complexity: O(n)

Solution:

C++ / BFS

 

C++ / DFS