Skip to content

Commit c1a72f0

Browse files
authored
Merge pull request #1362 from shreyash3087/add/leetcode-599
Docs: Added Solutions to Leetcode 599
2 parents fa38db7 + e9ad681 commit c1a72f0

File tree

2 files changed

+256
-1
lines changed

2 files changed

+256
-1
lines changed

dsa-problems/leetcode-problems/0500-0599.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,7 @@ export const problems =[
506506
"problemName": "599. Minimum Index Sum of Two Lists",
507507
"difficulty": "Easy",
508508
"leetCodeLink": "https://leetcode.com/problems/minimum-index-sum-of-two-lists",
509-
"solutionLink": "#"
509+
"solutionLink": "/dsa-solutions/lc-solutions/0500-0599/minimum-index-sum-of-two-lists"
510510
}
511511
]
512512

Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
---
2+
id: minimum-index-sum-of-two-lists
3+
title: Minimum Index Sum of Two Lists
4+
sidebar_label: 0599 - Minimum Index Sum of Two Lists
5+
tags:
6+
- Hash Table
7+
- Array
8+
- Heap (Priority Queue)
9+
description: "This is a solution to the Minimum Index Sum of Two Lists problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
14+
Given two arrays of strings `list1` and `list2`, find the **common strings with the least index sum**.
15+
16+
A **common string** is a string that appeared in both `list1` and `list2`.
17+
18+
A **common string with the least index sum** is a common string such that if it appeared at `list1[i]` and `list2[j]` then `i + j` should be the minimum value among all the other **common strings**.
19+
20+
Return all the **common strings with the least index sum**. Return the answer in **any order**.
21+
22+
### Examples
23+
**Example 1:**
24+
25+
```
26+
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
27+
Output: ["Shogun"]
28+
Explanation: The only common string is "Shogun".
29+
```
30+
31+
**Example 2:**
32+
33+
```
34+
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
35+
Output: ["Shogun"]
36+
Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1.
37+
```
38+
39+
### Constraints
40+
41+
- `1 <= list1.length, list2.length <= 1000`
42+
- `1 <= list1[i].length, list2[i].length <= 30`
43+
- `list1[i]` and `list2[i]` consist of spaces `' '` and English letters.
44+
- All the strings of `list1` are **unique**.
45+
- All the strings of `list2` are **unique**.
46+
- There is at least a common string between `list1` and `list2`.
47+
48+
## Solution for Minimum Index Sum of Two Lists
49+
### Approach #1 Using HashMap
50+
51+
In this approach, we compare every string in list1 and list2 by traversing over the whole list list2 for every string chosen from list1. We make use of a hashmap map, which contains elements of the form $$(sum:list_{sum})$$. Here, sum refers to the sum of indices of matching elements and $$list_{sum}$$ refers to the list of matching strings whose indices' sum equals sumsumsum.
52+
53+
Thus, while doing the comparisons, whenever a match between a string at $i^{th}$ index of list1 and $j^{th}$ index of list2 is found, we make an entry in the map corresponding to the sum $i+j$, if this entry isn't already present. If an entry with this sum already exists, we need to keep a track of all the strings which lead to the same index sum. Thus, we append the current string to the list of strings corresponding to sum $i+j$.
54+
55+
At the end, we traverse over the keys of the map and find out the list of strings corresponding to the key reprsenting the minimum sum.
56+
57+
## Code in Different Languages
58+
59+
<Tabs>
60+
<TabItem value="cpp" label="C++">
61+
<SolutionAuthor name="@Shreyash3087"/>
62+
63+
```cpp
64+
#include <iostream>
65+
#include <vector>
66+
#include <unordered_map>
67+
#include <string>
68+
#include <algorithm>
69+
70+
class Solution {
71+
public:
72+
std::vector<std::string> findRestaurant(std::vector<std::string>& list1, std::vector<std::string>& list2) {
73+
std::unordered_map<int, std::vector<std::string>> map;
74+
for (int i = 0; i < list1.size(); ++i) {
75+
for (int j = 0; j < list2.size(); ++j) {
76+
if (list1[i] == list2[j]) {
77+
int sum = i + j;
78+
map[sum].push_back(list1[i]);
79+
}
80+
}
81+
}
82+
int min_index_sum = INT_MAX;
83+
for (const auto& pair : map) {
84+
min_index_sum = std::min(min_index_sum, pair.first);
85+
}
86+
return map[min_index_sum];
87+
}
88+
};
89+
90+
```
91+
</TabItem>
92+
<TabItem value="java" label="Java">
93+
<SolutionAuthor name="@Shreyash3087"/>
94+
95+
```java
96+
public class Solution {
97+
public String[] findRestaurant(String[] list1, String[] list2) {
98+
HashMap < Integer, List < String >> map = new HashMap < > ();
99+
for (int i = 0; i < list1.length; i++) {
100+
for (int j = 0; j < list2.length; j++) {
101+
if (list1[i].equals(list2[j])) {
102+
if (!map.containsKey(i + j))
103+
map.put(i + j, new ArrayList < String > ());
104+
map.get(i + j).add(list1[i]);
105+
}
106+
}
107+
}
108+
int min_index_sum = Integer.MAX_VALUE;
109+
for (int key: map.keySet())
110+
min_index_sum = Math.min(min_index_sum, key);
111+
String[] res = new String[map.get(min_index_sum).size()];
112+
return map.get(min_index_sum).toArray(res);
113+
}
114+
}
115+
116+
```
117+
118+
</TabItem>
119+
<TabItem value="python" label="Python">
120+
<SolutionAuthor name="@Shreyash3087"/>
121+
122+
```python
123+
from typing import List
124+
from collections import defaultdict
125+
126+
class Solution:
127+
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
128+
index_map = defaultdict(list)
129+
for i, rest1 in enumerate(list1):
130+
for j, rest2 in enumerate(list2):
131+
if rest1 == rest2:
132+
index_map[i + j].append(rest1)
133+
134+
min_index_sum = min(index_map.keys())
135+
return index_map[min_index_sum]
136+
```
137+
</TabItem>
138+
</Tabs>
139+
140+
## Complexity Analysis
141+
142+
### Time Complexity: $O(l_1 * l_2 * x)$
143+
144+
> **Reason**: Every item of list1 is compared with all the items of list2. $l_1$ and $l_2$ are the lengths of list1 and list2 respectively. And x refers to average string length.
145+
146+
### Space Complexity: $O(l_1 * l_2 * x)$
147+
148+
> **Reason**: In worst case all items of list1 and list2 are same. In that case, hashmap size grows upto $l_1∗l_2∗x$, where x refers to average string length
149+
150+
### Approach #2 Without Using HashMap
151+
#### Algorithm
152+
153+
Another method could be to traverse the various sum(index sum) values and determine if any such string exists in list1 and list2 such that the sum of its indices in the two lists equals sum.
154+
155+
Now, we know that the value of index sum could range from 0 to m + n - 1. Here, m and n refer to the length of lists list1 and list2 respectively. Thus, we choose every value of sum in ascending order. For every sum chosen, we iterate over list1. Suppose, currently the string at the ith index in list1 is being considered. Now, in order for the index sum to be the one corresponding to matching strings in list1 and list2, the string at index j in list2 should match the string at index i in list1, such that sum = i + j.
156+
157+
Or, stating in other terms, the string at index j in list2 should be equal to the string at index i in list1, such that j = sum - i. Thus, for a particular sum and i (from list1), we can directly determine that we need to check the element at index j = sum - i in list2, instead of traversing the whole list2.
158+
159+
Doing such checks/comparisons, iterate over all the indices of list1 for every sum value chosen. Whenever a match occurs between list1 and list2, we put the matching string in a list res.
160+
161+
We do the same process of checking the strings for all the values of sum in ascending order. After completing every iteration over list1 for a particular sum, we check if the res list is empty or not. If it is empty, we need to continue the process with the next sum value considered. If not, the current res gives the required list with minimum index sum. This is because we are already considering the index sum values in ascending order. So, the first list to be found is the required resultant list.
162+
163+
164+
## Code in Different Languages
165+
166+
<Tabs>
167+
<TabItem value="cpp" label="C++">
168+
<SolutionAuthor name="@Shreyash3087"/>
169+
170+
```cpp
171+
#include <vector>
172+
#include <string>
173+
#include <algorithm>
174+
175+
class Solution {
176+
public:
177+
std::vector<std::string> findRestaurant(std::vector<std::string>& list1, std::vector<std::string>& list2) {
178+
std::vector<std::string> res;
179+
int m = list1.size();
180+
int n = list2.size();
181+
for (int sum = 0; sum < m + n - 1; ++sum) {
182+
for (int i = 0; i <= sum; ++i) {
183+
if (i < m && sum - i < n && list1[i] == list2[sum - i]) {
184+
res.push_back(list1[i]);
185+
}
186+
}
187+
if (!res.empty()) {
188+
break;
189+
}
190+
}
191+
return res;
192+
}
193+
};
194+
195+
196+
```
197+
</TabItem>
198+
<TabItem value="java" label="Java">
199+
<SolutionAuthor name="@Shreyash3087"/>
200+
201+
```java
202+
public class Solution {
203+
public String[] findRestaurant(String[] list1, String[] list2) {
204+
List < String > res = new ArrayList < > ();
205+
for (int sum = 0; sum < list1.length + list2.length - 1; sum++) {
206+
for (int i = 0; i <= sum; i++) {
207+
if (i < list1.length && sum - i < list2.length && list1[i].equals(list2[sum - i]))
208+
res.add(list1[i]);
209+
}
210+
if (res.size() > 0)
211+
break;
212+
}
213+
return res.toArray(new String[res.size()]);
214+
}
215+
}
216+
```
217+
218+
</TabItem>
219+
<TabItem value="python" label="Python">
220+
<SolutionAuthor name="@Shreyash3087"/>
221+
222+
```python
223+
from typing import List
224+
225+
class Solution:
226+
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
227+
res = []
228+
m, n = len(list1), len(list2)
229+
for sum in range(m + n - 1):
230+
for i in range(sum + 1):
231+
if i < m and sum - i < n and list1[i] == list2[sum - i]:
232+
res.append(list1[i])
233+
if res:
234+
break
235+
return res
236+
237+
```
238+
</TabItem>
239+
</Tabs>
240+
241+
## Complexity Analysis
242+
243+
### Time Complexity: $O((l_1 * l_2)^2 * x)$
244+
245+
> **Reason**: There are two nested loops upto l1+l2 and string comparison takes x time. Here, x refers to the average string length.
246+
247+
### Space Complexity: $O(r * x)$
248+
249+
> **Reason**: res list is used to store the result. Assuming r is the length of resresres.
250+
251+
## References
252+
253+
- **LeetCode Problem**: [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/)
254+
255+
- **Solution Link**: [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/solutions/)

0 commit comments

Comments
 (0)