Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to select the next item with the highest value per weight ratio in a greedy approach.
DSA Go
func selectNextItem(items []Item) Item {
var best Item
bestRatio := 0.0
for _, item := range items {
ratio := float64(item.Value) / float64(item.Weight)
if ratio > [1] {
best = item
bestRatio = ratio
}
}
return best
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing ratio to 0 instead of bestRatio.
Using item.Value or item.Weight directly in the if condition.
✗ Incorrect
We compare the current item's value-to-weight ratio with the bestRatio found so far to pick the best item greedily.
2fill in blank
mediumComplete the code to check if the greedy solution is optimal by comparing total weight with capacity.
DSA Go
func canAddItem(currentWeight, itemWeight, capacity int) bool {
return currentWeight + itemWeight [1] capacity
}Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of <= causes off-by-one errors.
Using > or >= reverses the logic.
✗ Incorrect
We allow adding the item if total weight does not exceed capacity, so use <=.
3fill in blank
hardFix the error in the greedy coin change function to correctly pick the largest coin not exceeding the amount.
DSA Go
func greedyCoinChange(coins []int, amount int) []int {
var result []int
for _, coin := range coins {
for amount [1] coin {
amount -= coin
result = append(result, coin)
}
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of >= causes the loop to never run.
Using > excludes the case when amount equals coin.
✗ Incorrect
We subtract coin from amount while amount is greater than or equal to coin value.
4fill in blank
hardFill both blanks to create a map comprehension that filters words longer than 3 characters and maps them to their lengths.
DSA Go
lengths := map[string]int{}
for _, word := range words {
if len(word) [1] 3 {
lengths[word] = [2]
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using == or < instead of > in the condition.
Assigning word instead of len(word) in the map.
✗ Incorrect
We check if word length is greater than 3 and map word to its length.
5fill in blank
hardFill all three blanks to create a map of uppercase words to their lengths, filtering words longer than 4 characters.
DSA Go
result := map[string]int{}
for _, word := range words {
if len(word) [1] 4 {
result[[2]] = [3]
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using <= instead of > in the condition.
Assigning word instead of uppercase word as key.
Assigning word instead of len(word) as value.
✗ Incorrect
We filter words longer than 4, map uppercase word to its length.
