OAmaster
— / 17已做

In the nation of Coderland, the layout of the cities can be depicted as a tree structure with totalCities numbered from 1 to totalCities. These cities are interconnected by totalCities - 1 two-way routes, where the i-th route links cityStart[i] with cityEnd[i]. The ruler of Coderland intends to install one of monumentTypes unique monuments in each city. However, the following condition must be satisfied: No two directly connected cities or two cities that share a common neighboring city can have identical monument types. Your task is to calculate the total number of valid configurations for placing monuments in every city based on these rules. Since the resulting number could be extremely large, return the answer modulo (10⁹ + 7). Two cities are regarded as adjacent if there is a direct connection between them via a route. Parameters: int monumentTypes: The number of distinct monument styles available. int totalCities: The total number of cities in the kingdom. int[] routeStart: An array representing the starting city of each road. int[] routeEnd: An array representing the ending city of each road. Returns: int: The number of valid ways to construct the monuments, computed modulo (10⁹ + 7).

解法

树染色:根任选一节点;颜色数 m。根有 m 种;每个非根节点不能与父、祖父、兄弟颜色相同。每对父子边贡献 (m − 1 − 已被祖父占据 1 个 − 已被同父兄弟占据)。可证答案 = m · (m-1) · ∏_v (m-1-d_v)^? — 简化版本:树形 DP。

from collections import defaultdict
from typing import List

MOD = 10 ** 9 + 7

def build_monuments(monument_types: int, total_cities: int, route_start: List[int], route_end: List[int]) -> int:
    g = defaultdict(list)
    for u, v in zip(route_start, route_end):
        g[u].append(v); g[v].append(u)
    # BFS from node 1; for each non-root node, count of (forbidden colors) = 1 (parent) + (siblings already colored) + (grandparent if exists)
    # Approximate: m * (m-1)^(深度=1) * ∏ (m - 1 - sibling_idx - grand_constraint)
    # We use a simple BFS-order counting.
    ans = monument_types
    visited = {1}
    color_assigned = {1: 0}  # placeholder
    from collections import deque
    parent = {1: None}; grand = {1: None}
    q = deque([1])
    sibling_done = defaultdict(int)
    while q:
        u = q.popleft()
        for v in g[u]:
            if v not in visited:
                visited.add(v)
                parent[v] = u
                grand[v] = parent[u]
                forbidden = 1  # parent
                if grand[v] is not None: forbidden += 1
                forbidden += sibling_done[u]
                choices = max(0, monument_types - forbidden)
                ans = ans * choices % MOD
                sibling_done[u] += 1
                q.append(v)
    return ans
import java.util.*;

class Solution {
    static final long MOD = 1_000_000_007L;
    public int buildMonuments(int monumentTypes, int totalCities, int[] routeStart, int[] routeEnd) {
        Map<Integer, List<Integer>> g = new HashMap<>();
        for (int i = 0; i < routeStart.length; i++) {
            g.computeIfAbsent(routeStart[i], k -> new ArrayList<>()).add(routeEnd[i]);
            g.computeIfAbsent(routeEnd[i], k -> new ArrayList<>()).add(routeStart[i]);
        }
        long ans = monumentTypes;
        Set<Integer> visited = new HashSet<>(); visited.add(1);
        Map<Integer, Integer> parent = new HashMap<>(), grand = new HashMap<>();
        Map<Integer, Integer> sibDone = new HashMap<>();
        parent.put(1, 0);
        Deque<Integer> q = new ArrayDeque<>(); q.add(1);
        while (!q.isEmpty()) {
            int u = q.poll();
            for (int v : g.getOrDefault(u, Collections.emptyList())) {
                if (visited.add(v)) {
                    parent.put(v, u);
                    grand.put(v, parent.get(u));
                    int forbid = 1 + (grand.get(v) != 0 ? 1 : 0) + sibDone.getOrDefault(u, 0);
                    int choices = Math.max(0, monumentTypes - forbid);
                    ans = ans * choices % MOD;
                    sibDone.merge(u, 1, Integer::sum);
                    q.add(v);
                }
            }
        }
        return (int) ans;
    }
}
#include <bits/stdc++.h>
using namespace std;

class Solution {
    static constexpr long long MOD = 1000000007;
public:
    int buildMonuments(int monumentTypes, int totalCities, vector<int>& routeStart, vector<int>& routeEnd) {
        unordered_map<int, vector<int>> g;
        for (int i = 0; i < (int)routeStart.size(); i++) { g[routeStart[i]].push_back(routeEnd[i]); g[routeEnd[i]].push_back(routeStart[i]); }
        long long ans = monumentTypes;
        unordered_set<int> visited; visited.insert(1);
        unordered_map<int, int> parent, grand, sibDone;
        parent[1] = 0;
        queue<int> q; q.push(1);
        while (!q.empty()) {
            int u = q.front(); q.pop();
            for (int v : g[u]) {
                if (visited.insert(v).second) {
                    parent[v] = u;
                    grand[v] = parent[u];
                    int forbid = 1 + (grand[v] != 0 ? 1 : 0) + sibDone[u];
                    int choices = max(0, monumentTypes - forbid);
                    ans = ans * choices % MOD;
                    sibDone[u]++;
                    q.push(v);
                }
            }
        }
        return (int) ans;
    }
};

The other question asked in the same batch is LC647. After a user logs in, they receive a token. If the token exceeds the system-defined expiration period (expiryLimit), it becomes invalid. However, if the token is reset within the period, the expiration time is extended. Valid tokens can be reset repeatedly. Expired or non-existent tokens will have their reset operations ignored. Expired tokens cannot be used again. Command format: [type, token_id, T] type 0 (create): Create a token with an expiration time set to T + expiryLimit. type 1 (reset): Extend the token's expiration time to T + expiryLimit. Initially, there are no tokens. Process the requests in order and determine how many tokens are still valid at the maximum time point. Function Description Complete the function countValidTokens in the editor. countValidTokens has the following parameters:

    1. int expiryLimit: the system-defined expiration period
    1. int[][] commands: a 2D array of commands where each command is of the format [type, token_id, T] Returns int: the number of valid tokens at the maximum time point

解法

维护 expire[token_id] = 该 token 当前过期时间。type=0 创建:set expire[id] = T + expiryLimit;type=1 reset:若 expire 存在且 T ≤ expireid则 expire[id] = T + expiryLimit,否则忽略。处理完后,maxTime = max(T);统计 expire[id] > maxTime 的 id 数。

from typing import List

def count_valid_tokens(expiry_limit: int, commands: List[List[int]]) -> int:
    expire: dict = {}
    max_t = 0
    for typ, tid, T in commands:
        max_t = max(max_t, T)
        if typ == 0:
            expire[tid] = T + expiry_limit
        else:
            if tid in expire and T <= expire[tid]:
                expire[tid] = T + expiry_limit
    return sum(1 for e in expire.values() if e > max_t)
import java.util.*;

class Solution {
    public int countValidTokens(int expiryLimit, int[][] commands) {
        Map<Integer, Integer> expire = new HashMap<>();
        int maxT = 0;
        for (int[] c : commands) {
            maxT = Math.max(maxT, c[2]);
            if (c[0] == 0) expire.put(c[1], c[2] + expiryLimit);
            else if (expire.containsKey(c[1]) && c[2] <= expire.get(c[1])) expire.put(c[1], c[2] + expiryLimit);
        }
        int cnt = 0;
        for (int e : expire.values()) if (e > maxT) cnt++;
        return cnt;
    }
}
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int countValidTokens(int expiryLimit, vector<vector<int>>& commands) {
        unordered_map<int, int> expire;
        int maxT = 0;
        for (auto& c : commands) {
            maxT = max(maxT, c[2]);
            if (c[0] == 0) expire[c[1]] = c[2] + expiryLimit;
            else if (expire.count(c[1]) && c[2] <= expire[c[1]]) expire[c[1]] = c[2] + expiryLimit;
        }
        int cnt = 0;
        for (auto& [k, e] : expire) if (e > maxT) cnt++;
        return cnt;
    }
};

There are n customers and m products. Each customer gives a rating r[i] for each of the i'th product (This is stored in ratings 2d matrix). The task is to choose (n-2) products such that the min of the mx array is maximized. Where, mx[j] be the max rating given by a customer j for among all selected products.

Constraints

  • 2 ≤ n ≤ m ≤ 10⁵
  • 0 ≤ ratings[i][j] ≤ 10⁹
  • These constraints are based on memory; they might not be correct

Example 1

Input:

n = 4
m = 4
ratings = [[3,4,2,2],[3,3,3,4],[2,4,2,3],[4,2,4,2]]

Output:

3

Explanation: Here we have 4 customers and 4 products. Customer 1 gives rating of ratings[0] for the 4 products and so on. We need to choose (n-2) products such that the min of the mx array is maximized. If we choose product 0 and 1: min(max(3,4),max(3,3),max(2,4),max(4,2)) = 3 If we choose product 0 and 2: min(max(3,2),max(3,3),max(2,2),max(4,4)) = 2 If we choose product 0 and 3: min(max(3,2),max(3,4),max(2,3),max(4,2)) = 3 If we choose product 1 and 2: min(max(4,2),max(3,3),max(4,2),max(2,4)) = 3 If we choose product 1 and 3: min(max(4,2),max(3,4),max(4,3),max(2,2)) = 2 If we choose product 2 and 3: min(max(2,2),max(3,4),max(2,3),max(4,2)) = 2 Output = max(3,2,3,3,2,2) = 3

解法

选 (n-2) 个产品 = 去除 2 个;m 较小时枚举 C(m, 2) 种去除组合,对每个组合算 min(max(rating[c][j]) for j in 保留集合),取最大。O(m² · n)。

from typing import List

def choose_max_min_rating(n: int, m: int, ratings: List[List[int]]) -> int:
    best = -1
    for a in range(m):
        for b in range(a + 1, m):
            mn = float('inf')
            for c in range(n):
                mx = max(ratings[c][j] for j in range(m) if j != a and j != b)
                mn = min(mn, mx)
            best = max(best, mn)
    return best
class Solution {
    public int chooseMaxMinRating(int n, int m, int[][] ratings) {
        int best = -1;
        for (int a = 0; a < m; a++) for (int b = a + 1; b < m; b++) {
            int mn = Integer.MAX_VALUE;
            for (int c = 0; c < n; c++) {
                int mx = 0;
                for (int j = 0; j < m; j++) if (j != a && j != b) mx = Math.max(mx, ratings[c][j]);
                mn = Math.min(mn, mx);
            }
            best = Math.max(best, mn);
        }
        return best;
    }
}
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int chooseMaxMinRating(int n, int m, vector<vector<int>>& ratings) {
        int best = -1;
        for (int a = 0; a < m; a++) for (int b = a + 1; b < m; b++) {
            int mn = INT_MAX;
            for (int c = 0; c < n; c++) {
                int mx = 0;
                for (int j = 0; j < m; j++) if (j != a && j != b) mx = max(mx, ratings[c][j]);
                mn = min(mn, mx);
            }
            best = max(best, mn);
        }
        return best;
    }
};

You are given two N-sided dic

Example 1

Input:

P = [1, 2, 4]
Q = [2, 2, 5]

Output:

[-0, -0, -0]

Explanation: Hello - Example output is just a placeholder to let the system not complain about missing output :)

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

As we can see from the source image, this question is from LC636 :) The other question asked together was LC339 :) On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1. Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with its ID, whether it started or ended, and the timestamp. You are given a list logs, where logs[i] represents the ith log message formatted as a string "{function_id}:{start/end}:{timestamp}". For example, "0:start:3" means a function call with function ID 0 started at the beginning of timestamp 3, and "1:end:2" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively. A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3. Return the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.

Constraints

  • `1 0
  • No two start events will happen at the same timestamp.
  • No two end events will happen at the same timestamp.
  • Each function has an "end" log for each "start" log.

Example 1

Input:

n = 2
logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]

Output:

[3,4]

Explanation: Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1. Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5. Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time. So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.

Example 2

Input:

n = 1
logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]

Output:

[8]

Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls itself again. Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time. Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time. So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.

Example 3

Input:

n = 2
logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]

Output:

[7,1]

Explanation: Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself. Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time. Function 0 (initial call) resumes execution then immediately calls function 1. Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6. Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time. So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an n x n matrix of integers and an integer value, threshold, determine the maximum size of a square sub-matrix such that for all square sub-matrices of that size, the sum of all elements in each square sub-matrix is less than or equal to the value threshold. Function Description Complete the function maxSubmatrixSumSize in the editor. maxSubmatrixSumSize has the following parameters:

    1. int[][] matrix: a 2D array of integers
    1. int threshold: the maximum sum of all square sub-matrices of a size must be less than or equal to this integer value Returns int: the maximum size of the square sub-matrix

Example 1

Input:

matrix = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]
threshold = 4

Output:

0

Explanation: The maximum 1x1 matrix has a sum of 4. If threshold < 4 there is no size square sub-matrix that satisfies the condition. The answer is 0. 1x1 sub-matrices Maximum sub-matrix sum = 4

Example 2

Input:

matrix = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]
threshold = 14

Output:

1

Explanation: The maximum 2x2 matrix has a sum of 14. If 4 ≤ threshold < 14, the maximum size of the square sub-matrix is 1. 2x2 sub-matrices Maximum sub-matrix sum = 14 (3 + 3 + 4 + 4 = 14)

Example 3

Input:

matrix = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]
threshold = 27

Output:

2

Explanation: The maximum 3x3 matrix has a sum of 27. If 14 ≤ threshold < 27, the maximum size of the square sub-matrix is 2. 3x3 sub-matrices Maximum sub-matrix sum = 27 (2 + 2 + 2 + 3 + 3 + 3 + 4 + 4 + 4 = 27)

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n machines each equipped with m power units (m ≥ 2). The power of the jthunit in the i-thmachine is denoted as machine_power[i][j]. The strength of a machine is defined as the minimum power among all its power units. We want to maximize the sum of the strength of all possible machines. For this, we can perform a 3-step operation multiple times (possibly 0): Select a machine that has not yet been marked. Transfer any one power unit from the selected machine to any other machine. Mark the selected machine, and it cannot be chosen for further operations. However, a marked machine can still receive power units from other machines. Find the max sum of the strength of all machines. Note: Each machine can transfer at most one power unit during the entire process, only when it is unmarked. A machine can receive power units from multiple other machines, even after it has been marked. The operation can be performed multiple times, but only unmarked machines can be selected during each operation.

Constraints

TO-DO</cod

Example 1

Input:

n = 3
m = 2
machine_power = [[1,5],[4,3],[2,10]]

Output:

16

Explanation: The operation are as follows: Select machine 1 and transfer the unit with power 1 to machine 2. now machine powers are = [[5],[1,4,3],[2,10]] Select machine 3 and transfer the unit with power 2 to machine 2 now machine powers are = [[5],[1,2,4,3],[10]] The sum of strenght is min(5) + min(1,2,4,3) + min(10) = 16 Return 16.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are developing a messaging system that needs to process messages in a specific order. Each message has a timestamp and a priority level (1 to 5, where 1 is highest priority). Messages should be processed based on the following rules: higher priority messages should be processed first, and among messages with the same priority, earlier timestamps should be processed first. Write a function that takes an array of messages (each containing timestamp and priority) and returns them in the correct processing order. Each message in the input array will be in the format: 'timestamp:priority'. Function Description Complete the function processMessages in the editor. processMessages has the following parameter:

  • String[] messages: an array of strings where each string is in the format 'timestamp:priority' Returns String[]: an array of messages in the correct processing order Requirements: Function should accept an array of strings as input. Each string will be in format 'timestamp:priority' (e.g., '1045:2'). Timestamp will be a 4-digit number (0000-9999). Priority will be a single digit from 1-5.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an integer array nums, return the number of elements th

Constraints

0 ≤ nums.length ≤ 1000 -100000 ≤ nums[i] ≤ 100000

Example 1

Input:

nums = [1,2,4,7,10]

Output:

3

Explanation: The even numbers are 2, 4, and 10.

Example 2

Input:

nums = []

Output:

0

Explanation: The array is empty.

Example 3

Input:

nums = [-3,-2,0,5,8]

Output:

3

Explanation: The even numbers are -2, 0, and 8.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an integer array nums, return the maximum absolute d

Constraints

1 ≤ nums.length ≤ 1000 -100000 ≤ nums[i] ≤ 100000

Example 1

Input:

nums = [3,8,2,10]

Output:

8

Explanation: The adjacent absolute differences are 5, 6, and 8, so the maximum is 8.

Example 2

Input:

nums = [7]

Output:

0

Explanation: There are no adjacent pairs.

Example 3

Input:

nums = [-4,-10,6,1]

Output:

16

Explanation: The largest adjacent absolute difference is between -10 and 6.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array of integers nums and an integer target, return <em

Constraints

2 -10 `-10 Only one valid answer exists.

Example 1

Input:

nums = [2,7, 11, 15]
target = 9

Output:

[0, 1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2

Input:

nums = [2,7]
target = 9

Output:

[0, 1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Initially, all applications are deployed on n servers, with varying load handling capacities. The developers want to divide the n servers into clusters of cluster_size each such that the servers in each cluster have the same load-handling capacity. To achieve this, developers can recalibrate one or more servers. In one move, any server can be reconfigured to handle a lesser load than its current capacity, i.e., in one move capacity[i], can be changed to any integer value less than capacity[i]. Given the initial capacities of the servers, in an array, capacity, of size n, and an integer cluster_size, find the minimum number of moves required to divide the servers into clusters. Function Description Complete the function getMinimumMoves in the editor below. getMinimumMoves has the following parameters:

  • int capacity[n]: the initial load-handling capacity of the servers
  • int cluster_size: the size of each cluster Returns int: minimum moves to divide the n servers into clusters as mentioned above A supa huge thank-you to a wonderful friend for all the help!

Constraints

  • 1 ≤ n ≤ 2 x 10⁵
  • 1 ≤ capacity[i] ≤ 10⁹
  • 1 ≤ cluster_size ≤ n
  • n is a multiple of cluster_size.

Example 1

Input:

capacity = [4, 2, 4, 4, 7, 4]
cluster_size = 3

Output:

2

Explanation: At least 2 moves to get clusters of size 3 each..

Example 2

Input:

capacity = [1,2,2,3,4,5,5,6]
cluster_size = 4

Output:

5

Explanation: 5 changes to get [1,1,1,1,2,2,2,2].

Example 3

Input:

capacity = [1,1,3,2]
cluster_size = 2

Output:

1

Explanation: 1 change to get [1,1,2,2].

Example 4

Input:

capacity = [5, 4, 2, 7, 1, 1, 5, 3, 4, 7, 4, 3, 6, 2, 1, 7, 5, 7, 5, 6, 5, 2, 1, 1, 1, 3, 4, 1, 7, 3]
cluster_size = 5

Output:

5

Explanation: 5 changes to get [1,1,1,1,1,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,7,7,7,7,7].

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The first line of the input consists of two space-separated integers - num and numCord, representing the number of pickup locations (N) and number of coordinates for a pick up location (numCord (P) is always equal to two), respectively. The next N lines consist of P space-separated integers - pickX and pickY, representing the X and Y coordinates of a pickup location, respectively. The next line consists of an integer - baseXₒ representing the X coordinate of the base location. The next line consists of an integer - baseYₒ representing the Y coordinate of the base location. Print an integer representing the minimum number of routes connecting all the pickup locations to the base location. Thanks a bazillion, spike!

Constraints

  • 1 ≤ num ≤ 10⁵
  • -10³ ≤ pickX, pickY, baseXₒ, baseYₒ ≤ 10³

Example 1

Input:

pickupLocations = [[1, 1], [-1, 1], [2, 3]]
baseX = 0
baseY = 0

Output:

3

Explanation: From the base coordinate (0,0) three different routes will cover all the pickup locations.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given two boxes of chocolate containing A and B chocolates representing the number of chocolates Alex and Drake have, respectively. Drake is the younger child and will only be happy if he receives a multiple of what Alex gets. You decided to buy some extra chocolates. Mathematically, The share of chocolates will be: k * (A + X) = (B + Y) for some non-negative integer X and Y and some positive integer k. What is the minimum number of extra chocolates (X + Y) that you need to buy? Note: The original chocolates (A and B) cannot be transferred among each other. Function Description Complete the function solution. The function takes 2 parameters and returns the solution:

  • A: Represents the number of initial chocolates in Alex's box
  • B: Represents the number of initial chocolates in Drake's box Limits Time Limit: 1.0 sec(s) for each input file Memory Limit: 256 MB Source Limit: 1024 KB Scoring Score is assigned if any testcase passes Allowed Languages [List of programming languages] Note: Your code must be able to print the sample output from the provided sample input. However, your code is run against multiple hidden test cases. Therefore, your code must pass these hidden test cases to solve the problem statement. Constraints

Constraints

0 < A,B < 10⁹

Example 1

Input:

A = 8
B = 16

Output:

0

Explanation: For the given test case, if you let X=0 and Y=0, then B+Y=16 will be a multiple of A+X=8. Here, you have X+Y=0, and there is no way to make X+Y smaller, so the answer is 0.

Example 2

Input:

A = 7
B = 37

Output:

4

Explanation: Adding 1 to A and 3 to B, we get A as 8 and B as 40, which satisfies the condition as k*A=B. k will be 5 here.

Example 3

Input:

A = 70
B = 229

Output:

9

Explanation: X will be 7 and Y will 2, k will end up becoming 3.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
  • Most Unique Elements (Part 1 :D
  • Most Unique Elements (Part 2 :O
  • Most Unique Elements (Part 3 :3 The 2nd parameter (boolean) is to use Jaccard Similarity instead of most common character. Refactor your code to select the strings that have the lowest average Jaccard Similarity when compared to every other string if this parameter is True. If the parameter is false you should still calculate the lowest proportion in Part 1. The rest of your code is the same as Part 1: return a string composed of the characters that are uniquely present in the selected strings across the entire list. For this part, assume there’s a function imported that calculates the pair-wise jaccard similarity between two strings (returns a number between 0 and 1): 1 -> true; 0 -> false Function Definition: def jaccard(string1, string2): return 0 Make sure the tests for Part 1 still pass. Hi~ There is no example test case coming with the source, so the example below is just a placeholder. The problem statement and function definition should give us a clear idea of what this problem is asking~

Constraints

  • :)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
  • Most Unique Elements (Part 1 :D
  • Most Unique Elements (Part 2 :O
  • Most Unique Elements (Part 3 :3 If time allows, the company'd like us to finish Part 3 :) Implement the jaccard function. The Jaccard Similarity is a pair-wise comparison calculated with the formula: jaccard(A, B) = intersection(A, B) / union(A, B) The intersection is the set of characters that are present in both strings together, including repeats. The union is the smallest set that contains all characters found in either string, including repeats. Thanks a ton to the kind soul who shared the source!

Constraints

  • :)

Example 1

Input:

string1 = "baa"
string2 = "abbc"

Output:

0.4

Explanation: intersection(S1, S2) = "ab" union(S1, S2) = "aabbc" J(S1, S2) = len("ab") / len("aabbc") = 2/5

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
  • Most Unique Elements (Part 1 :D
  • Most Unique Elements (Part 2 :O
  • Most Unique Elements (Part 3 :3 Your goal is to find unlikely characters in a group of strings. Given a list of strings, select the strings where the most common character has the smallest proportion in its string. If multiple strings have the same proportion, select all the strings with the smallest proportion. Return a new string composed of the characters that are only present in the selected strings. Thanks a lot to the friend who shared the source!

Constraints

  • :)

Example 1

Input:

group = ["aba", "ab", "abbcdd"]

Output:

"cdd"

Explanation:

  • "aba": most common character is 'a', with proportion 2/3
  • "ab": most common characters are 'a' and 'b', with proportion 1/2
  • "abbcdd": most common character are 'b' and 'd', with proportion 2/6 The smallest proportion is 2/6, so we select the last string "abbcdd" and return the characters that are only present in this string: "cdd"
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 14 道题的解法

题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.

Pro 解锁全部
  • 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
  • 📊个人 dashboard + 进度可视化 + 14 天活跃图
  • 📝题目笔记跨设备同步 + 个人复盘库
  • 🔓随时取消下次续费, Stripe Customer Portal 自助管理
$12/月($98/年, 一次付清省 32%)

≈ 北美 SWE 工资 10 分钟 · LeetCode Premium $35/月 的 23%