man.god96's blog

By man.god96, history, 2 months ago, In English,

This is regarding https://leetcode.com/problems/coin-change/. It is a simple DP problem. And I wrote the following code for it using map for memoization. But it gave Time limit extended -

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n = coins.size();
        map<int,int> dp;
        dp[0]=0;
        for(int i=1;i<=amount;i++) {
            dp[i]=amount+1;
            for(int j=0;j<n;j++) {
                if(i>=coins[j]) dp[i] = min(dp[i],dp[i-coins[j]]+1);
            }
        }
        return dp[amount]>amount ? -1:dp[amount];        
    }
};

But when I changed map to vector, it gets ACCEPTED (Following code got accepted)-

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int Max = amount + 1;
        vector<int> dp(amount + 1, Max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.size(); j++) {
                if (coins[j] <= i) {
                    dp[i] = min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
};

So why map gave TLE and not vector. When should we use map and when vector while solving DP problems? Any help will be appreciated.

 
 
 
 
  • Vote: I like it
  • -14
  • Vote: I do not like it

»
2 months ago, # |
  Vote: I like it +2 Vote: I do not like it

In a map, all operations (accessing an element, creating a new element, etc.) take $$$O(\log n)$$$ time to execute (where $$$n$$$ is the size of the container). In a vector, the same operations take $$$O(1)$$$ time.

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

O(logN) != O(1)

»
2 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

for further reading, refer to Antti Laaksonen, Guide to Competitive Programming , Chapter 5, Section 3, Experiments there are comparison tables, and explained in decent way

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Yeah right guys. Thanks. "The C++ standard library contains two map implementations that correspond to the set implementations: the structure map is based on a balanced binary tree and accessing elements takes O(logn) time, while the structure unordered_map uses hashing and accessing elements takes O(1) time on average."