question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
number-of-orders-in-the-backlog | Go solution using library in leetcode | go-solution-using-library-in-leetcode-by-ocfa | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Overmachine | NORMAL | 2024-09-28T02:42:52.545091+00:00 | 2024-09-28T02:42:52.545134+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nimport (\n pq "github.com/emirpasic/gods/v2/queues/priorityqueue"\n"cmp"\n"math"\n)\n\ntype Order struct {\n Price int\n Amount int\n}\n\nfunc getNumberOfBacklogOrders(orders [][]int) int {\n buysQueue := pq.NewWith(maxPriority)\n sellsQueue := pq.NewWith(minPriority)\n \n for _, ord := range orders {\n curPrice := ord[0]\n curAmount := ord[1]\n orderType := ord[2]\n\n if orderType == 0 {\n for sellsQueue.Size() > 0 && curAmount > 0 {\n sell, _:= sellsQueue.Dequeue()\n \n if sell.Price > curPrice {\n sellsQueue.Enqueue(sell)\n break;\n }\n\n if sell.Amount > curAmount {\n sell.Amount = sell.Amount - curAmount\n curAmount = 0\n sellsQueue.Enqueue(sell)\n } else if sell.Amount <= curAmount {\n curAmount = curAmount - sell.Amount\n }\n }\n if curAmount > 0 {\n buysQueue.Enqueue(Order{Price: curPrice, Amount: curAmount})\n }\n }\n\n if orderType == 1 {\n for buysQueue.Size() > 0 && curAmount > 0 {\n buy, _:= buysQueue.Dequeue()\n\n if buy.Price < curPrice {\n buysQueue.Enqueue(buy)\n break;\n }\n\n if buy.Amount > curAmount {\n buy.Amount = buy.Amount - curAmount\n curAmount = 0\n buysQueue.Enqueue(buy)\n } else if buy.Amount <= curAmount {\n curAmount = curAmount - buy.Amount\n }\n }\n if curAmount > 0 {\n sellsQueue.Enqueue(Order{Price: curPrice, Amount: curAmount})\n }\n }\n }\n \n res := 0\n for buysQueue.Size() > 0 {\n buy, _ := buysQueue.Dequeue()\n res = res + buy.Amount\n }\n\n for sellsQueue.Size() > 0 {\n sell, _ := sellsQueue.Dequeue()\n res = res + sell.Amount\n }\n \n return (res) % int(math.Pow10(9) + 7.0)\n}\n\nfunc maxPriority(a, b Order) int {\n return -cmp.Compare(a.Price, b.Price)\n}\n\nfunc minPriority(a, b Order) int {\n return cmp.Compare(a.Price, b.Price)\n}\n``` | 0 | 0 | ['Go'] | 0 |
number-of-orders-in-the-backlog | Javascript solution | javascript-solution-by-overmachine-dcpu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Overmachine | NORMAL | 2024-09-28T00:54:04.838065+00:00 | 2024-09-28T00:54:04.838097+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[][]} orders\n * @return {number}\n */\nvar getNumberOfBacklogOrders = function(orders) {\n const buysQueue = new MaxPriorityQueue({ priority: (bid) => bid[0] });\n const sellsQueue = new MinPriorityQueue({ priority: (bid) => bid[0] })\n\n for (let [price, amount, orderType] of orders) {\n if (orderType === 0) {\n\n while(!sellsQueue.isEmpty() && amount > 0) {\n let [sellPrice, sellAmount] = sellsQueue.dequeue().element\n \n if(sellPrice > price) {\n sellsQueue.enqueue([sellPrice, sellAmount]);\n break;\n }\n if(sellAmount > amount) {\n sellAmount -= amount;\n amount = 0;\n sellsQueue.enqueue([sellPrice, sellAmount]);\n } else if (sellAmount <= amount) {\n amount -= sellAmount;\n }\n\n }\n if(amount > 0) {\n buysQueue.enqueue([price, amount])\n }\n }\n if (orderType === 1) {\n\n while(!buysQueue.isEmpty() && amount > 0) {\n let [buyPrice, buyAmount] = buysQueue.dequeue().element\n \n if(buyPrice < price) {\n buysQueue.enqueue([buyPrice, buyAmount]);\n break;\n }\n if(buyAmount > amount) {\n buyAmount -= amount;\n amount = 0;\n buysQueue.enqueue([buyPrice, buyAmount]);\n } else if (buyAmount <= amount) {\n amount -= buyAmount;\n }\n\n }\n if(amount > 0) {\n sellsQueue.enqueue([price, amount])\n }\n }\n }\n\n let backlogtotal = 0\n\n while(!buysQueue.isEmpty()) {\n const [price, amount] = buysQueue.dequeue().element;\n backlogtotal += amount;\n }\n while(!sellsQueue.isEmpty()) {\n const [price, amount] = sellsQueue.dequeue().element;\n backlogtotal += amount;\n }\n\n return backlogtotal % (Math.pow(10,9) + 7)\n};\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
number-of-orders-in-the-backlog | C# Priority Queue-Based Solution | c-priority-queue-based-solution-by-getri-0ckc | Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem of processing orders and managing the backlog, we can use two prio | GetRid | NORMAL | 2024-09-09T15:16:14.386501+00:00 | 2024-09-09T15:16:14.386544+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem of processing orders and managing the backlog, we can use two priority queues (heaps) to efficiently match buy and sell orders:\n\nBuy Orders: We need a max-heap to store the buy orders because we want to match the highest-priced buy order first.\nSell Orders: We need a min-heap to store the sell orders because we want to match the lowest-priced sell order first.\n___\n\n# Approach\n<!-- Describe your approach to solving the problem. -->Priority Queues:\n\nbuyBacklog: A max-heap stores buy orders with the highest prices at the top.\nsellBacklog: A min-heap stores sell orders with the lowest prices at the top.\nOrder Matching:\n\nFor buy orders, we check if they can be matched with the smallest sell order in the sellBacklog.\nFor sell orders, we check if they can be matched with the largest buy order in the buyBacklog.\nMatching continues until either the current order is exhausted or no more valid matches exist.\nHandling Remaining Orders:\n\nIf there are any unprocessed orders after matching, they are added to their respective backlogs (buy or sell).\n\nTotal Backlog Calculation:\nAfter processing all orders, we sum the remaining orders in both backlogs and return the result modulo 10^9 + 7.\n___\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n log n), where \'n\' is the number of orders.\n____\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n), due to the space used by the priority queues for storing and buying sell orders.\n___\n\n# Code\n```csharp []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n private const int MOD = 1000000007;\n\n public int GetNumberOfBacklogOrders(int[][] orders) {\n // Max-heap for buy orders (store negative price to simulate max-heap using PriorityQueue)\n PriorityQueue<(int price, int amount), int> buyBacklog = new PriorityQueue<(int price, int amount), int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));\n \n // Min-heap for sell orders\n PriorityQueue<(int price, int amount), int> sellBacklog = new PriorityQueue<(int price, int amount), int>();\n \n foreach (var order in orders) {\n int price = order[0];\n int amount = order[1];\n int orderType = order[2];\n \n if (orderType == 0) {\n // Buy order\n while (amount > 0 && sellBacklog.Count > 0 && sellBacklog.Peek().price <= price) {\n var sellOrder = sellBacklog.Dequeue();\n int sellAmount = Math.Min(amount, sellOrder.amount);\n amount -= sellAmount;\n sellOrder.amount -= sellAmount;\n \n if (sellOrder.amount > 0) {\n sellBacklog.Enqueue(sellOrder, sellOrder.price);\n }\n }\n if (amount > 0) {\n buyBacklog.Enqueue((price, amount), price);\n }\n } else {\n // Sell order\n while (amount > 0 && buyBacklog.Count > 0 && buyBacklog.Peek().price >= price) {\n var buyOrder = buyBacklog.Dequeue();\n int buyAmount = Math.Min(amount, buyOrder.amount);\n amount -= buyAmount;\n buyOrder.amount -= buyAmount;\n \n if (buyOrder.amount > 0) {\n buyBacklog.Enqueue(buyOrder, buyOrder.price);\n }\n }\n if (amount > 0) {\n sellBacklog.Enqueue((price, amount), price);\n }\n }\n }\n\n // Calculate total backlog orders\n long totalOrders = 0;\n while (buyBacklog.Count > 0) {\n totalOrders = (totalOrders + buyBacklog.Dequeue().amount) % MOD;\n }\n while (sellBacklog.Count > 0) {\n totalOrders = (totalOrders + sellBacklog.Dequeue().amount) % MOD;\n }\n\n return (int)totalOrders;\n }\n}\n``` | 0 | 0 | ['Array', 'Heap (Priority Queue)', 'Simulation', 'C#'] | 0 |
number-of-orders-in-the-backlog | A intuitive solution in C++ | a-intuitive-solution-in-c-by-wkelvinson-usnz | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | wkelvinson | NORMAL | 2024-09-08T23:15:15.228182+00:00 | 2024-09-08T23:15:15.228213+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n int MOD = 1e9 + 7;\n priority_queue<pair<int, int>> buys;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> sells;\n for (auto & order : orders) {\n int price = order[0], amount = order[1], type = order[2];\n if (type == 0) {\n while (amount > 0 && !sells.empty() && sells.top().first <= price) {\n int sellPrice = sells.top().first, sellAmount = sells.top().second;\n if (sellAmount > amount) {\n sells.pop();\n sells.push({sellPrice, sellAmount - amount});\n amount = 0;\n \n } else {\n amount -= sellAmount;\n sells.pop();\n }\n }\n if (amount > 0) {\n buys.push({price, amount});\n }\n } else {\n while (amount > 0 && !buys.empty() && buys.top().first >= price) {\n int buyPrice = buys.top().first, buyAmount = buys.top().second;\n if (buyAmount > amount) {\n buys.pop();\n buys.push({buyPrice, buyAmount - amount});\n amount = 0;\n \n } else {\n amount -= buyAmount;\n buys.pop();\n }\n }\n if (amount > 0) {\n sells.push({price, amount});\n }\n }\n }\n\n\n long long sum = 0LL;\n while (!buys.empty()) {\n sum = sum + buys.top().second % MOD;\n buys.pop();\n }\n\n while (!sells.empty()) {\n sum = sum + sells.top().second % MOD;\n sells.pop();\n }\n return sum % MOD;\n }\n \n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | EASY AND UNDERSTANDABLE | easy-and-understandable-by-animesh_maury-iiip | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Animesh_Maurya | NORMAL | 2024-09-06T06:59:37.029071+00:00 | 2024-09-06T06:59:37.029104+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<long long,long long>>buy;\n priority_queue<pair<long long,long long>,vector<pair<long long,long long>>,greater<pair<long long,long long>>>sell;\n for(auto it:orders){\n int price=it[0];\n int amount=it[1];\n int orderType=it[2];\n\n if(orderType == 0){\n while(sell.size()!=0){\n int p=sell.top().first;\n int am=sell.top().second;\n if(p<=price){\n if(amount == 0){\n break;\n }\n if(amount >= am){\n sell.pop();\n amount-=am;\n }else{\n sell.pop();\n sell.push({p,am-amount});\n amount=0;\n }\n }else{\n break;\n }\n\n }\n if(amount){\n buy.push({price,amount});\n }\n }\n else{\n while(buy.size()!=0){\n int p=buy.top().first;\n int am=buy.top().second;\n if(p>=price){\n if(amount == 0){\n break;\n }\n if(amount >= am){\n buy.pop();\n amount-=am;\n }else{\n buy.pop();\n buy.push({p,am-amount});\n amount=0;\n }\n }\n else{\n break;\n }\n \n }\n if(amount){\n sell.push({price,amount});\n }\n }\n }\n int ans=0;\n while(!sell.empty()){\n ans=(ans + (sell.top().second)% 1000000007) % 1000000007;\n sell.pop();\n }\n while(!buy.empty()){\n ans=(ans+ (buy.top().second) % 1000000007) % 1000000007;\n buy.pop();\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
number-of-orders-in-the-backlog | Using 2 heaps. Runtime top 90% Memory top 80% | using-2-heaps-runtime-top-90-memory-top-o7q9e | Approach\nThe solution uses two heaps: a max heap for buy orders and a min heap for sell orders, making it easy to get the highest buy price and the lowest sell | JonathanMeiri | NORMAL | 2024-08-29T10:26:55.049860+00:00 | 2024-08-29T10:26:55.049888+00:00 | 4 | false | # Approach\nThe solution uses two heaps: a max heap for buy orders and a min heap for sell orders, making it easy to get the highest buy price and the lowest sell price quickly. As we go through each order, we add it to the right heap based on whether it\'s a buy or sell order. We then check if any buy and sell orders can match, adjusting their amounts and removing them if they\'re fully matched. Once all orders are processed, we count up the amounts of the remaining unmatched orders in both heaps.\n\n# Complexity\n- Time complexity: O(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nstruct order_t{\n int price;\n int amount;\n order_t(int p, int a): price(p), amount(a) {};\n\n std::strong_ordering operator<=>(const order_t& other) const {\n return price <=> other.price; // Compare only the \'price\' field\n }\n};\n\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n std::vector<order_t> buy_heap; // max heap\n std::vector<order_t> sell_heap; // min heap\n for(const auto& order : orders) {\n if(order.at(2) == 0) {\n buy_heap.emplace_back(order.at(0), order.at(1));\n std::push_heap(buy_heap.begin(), buy_heap.end());\n } else {\n sell_heap.emplace_back(order.at(0), order.at(1));\n std::push_heap(sell_heap.begin(), sell_heap.end(), std::greater<>{});\n }\n\n // remove orders from backlog\n while(not(buy_heap.empty() or sell_heap.empty()) and buy_heap.front() >= sell_heap.front()){\n int amount = std::min(buy_heap.front().amount, sell_heap.front().amount);\n \n buy_heap[0].amount -= amount;\n sell_heap[0].amount -= amount;\n \n if(buy_heap[0].amount == 0){\n std::pop_heap(buy_heap.begin(),buy_heap.end());\n buy_heap.pop_back();\n }\n if(sell_heap[0].amount == 0) {\n std::pop_heap(sell_heap.begin(),sell_heap.end(), std::greater<>{});\n sell_heap.pop_back();\n }\n }\n }\n int count_backlog = 0;\n for(const auto& order : buy_heap){\n count_backlog += order.amount%1000000007;\n count_backlog %= 1000000007;\n }\n for(const auto& order : sell_heap){\n count_backlog += order.amount%1000000007;\n count_backlog %= 1000000007;\n }\n\n return count_backlog;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | [C++] Simply Solution - Very Easy to Understand | c-simply-solution-very-easy-to-understan-vnq3 | Intuition\nThis is a simple matching algorithm / orderbook problem, common in financial markets.\n\n# Approach\n Describe your approach to solving the problem. | leetcodegrindtt | NORMAL | 2024-08-16T01:41:26.775942+00:00 | 2024-08-16T01:41:26.775971+00:00 | 2 | false | # Intuition\nThis is a simple matching algorithm / orderbook problem, common in financial markets.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate:\n struct Order\n {\n private:\n bool buy_{};\n int price_{};\n int initialQty_{}, remainingQty_{};\n public:\n Order(const vector<int>& order) :\n buy_{ order.at(2) == 0 }, price_{ order.at(0) }, initialQty_{ order.at(1) },\n remainingQty_{ order.at(1) }\n { }\n\n bool IsBuy() const { return buy_; }\n void Fill(int quantity)\n {\n if (remainingQty_ - quantity < 0)\n throw std::logic_error("Cannot fill an order for more than the remaining quantity.");\n\n remainingQty_ -= quantity;\n }\n int RemainingQty() const { return remainingQty_; }\n int FilledQty() const { return initialQty_ - remainingQty_; }\n int Price() const { return price_; }\n bool IsFilled() const { return remainingQty_ == 0; }\n };\n\n using Orders = queue<Order>;\n using Asks = map<int, Orders, less<>>;\n using Bids = map<int, Orders, greater<>>;\n\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n\n Bids bids;\n Asks asks;\n\n size_t bidCount{};\n size_t askCount{};\n\n const auto Modulo = 1\'000\'000\'000 + 7;\n \n for (const auto& order : orders)\n {\n Order orderPointer{ order };\n\n if (orderPointer.IsBuy())\n {\n bids[orderPointer.Price()].push(orderPointer);\n bidCount++;\n }\n else\n {\n asks[orderPointer.Price()].push(orderPointer);\n askCount++;\n }\n\n while (!bids.empty() && !asks.empty())\n {\n auto& [bestBid, bidOrders] = *bids.begin();\n auto& [bestAsk, askOrders] = *asks.begin();\n\n if (bestBid < bestAsk)\n break;\n\n auto& bid = bidOrders.front();\n auto& ask = askOrders.front();\n\n auto fillQuantity = min(bid.RemainingQty(), ask.RemainingQty());\n\n bid.Fill(fillQuantity);\n ask.Fill(fillQuantity);\n\n if (bid.IsFilled())\n {\n bidCount--;\n bidOrders.pop();\n }\n\n if (bidOrders.empty())\n {\n bids.erase(bestBid);\n }\n\n if (ask.IsFilled())\n {\n askCount--;\n askOrders.pop();\n }\n\n if (askOrders.empty())\n {\n asks.erase(bestAsk);\n }\n }\n }\n\n size_t totalBids{}, totalAsks{};\n\n for (auto& [_, orders] : bids)\n {\n while (!orders.empty())\n {\n totalBids += orders.front().RemainingQty();\n orders.pop();\n }\n }\n\n for (auto& [_, orders] : asks)\n {\n while (!orders.empty())\n {\n totalAsks += orders.front().RemainingQty();\n orders.pop();\n }\n }\n\n return (totalBids + totalAsks) % Modulo;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | C++ priority queue | c-priority-queue-by-ckousik-kheg | Intuition\n Describe your first thoughts on how to solve this problem. \nThe requirement is to fetch the largest existing buy orders or the smallest existing se | ckousik | NORMAL | 2024-07-31T14:38:50.657263+00:00 | 2024-07-31T14:38:50.657290+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe requirement is to fetch the largest existing buy orders or the smallest existing sell orders. We need to be able to retrieve buy or sell orders in a sorted manner. A priority_queue/heap helps with this.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a max heap called `buy_queue` which stores a `(price, amount)` pair.\nCreate a min heap called `sell_queue` which stores a `(price, amount)` pair.\nWhenever we have a buy , pop from the sell queue until the price at the top of the heap is greater than the price on the order or the amount of orders at index i is 0.\nIf there are any remaining orders, push them to the buy_queue.\n\nSimilarly for the sell orders.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N*log(N))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n# Code\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n int mod = 1000000007;\n struct pairComparatorLess {\n bool operator()(const pair<int,int>& a, const pair<int, int>&b) {\n return a.first < b.first;\n }\n };\n \n struct pairComparatorGreater {\n bool operator()(const pair<int,int>& a, const pair<int, int>&b) {\n return b.first < a.first;\n }\n };\n priority_queue<pair<int, int>, vector<pair<int, int>>, pairComparatorLess> buy_queue;\n priority_queue<pair<int, int> , vector<pair<int, int>>, pairComparatorGreater> sell_queue;\n\n for(vector<int>& order: orders) {\n int price = order[0], amount = order[1], typ = order[2];\n switch (typ) {\n // buy\n case 0:\n while(!sell_queue.empty() && sell_queue.top().first <= price) {\n auto [sp, amt] = sell_queue.top();\n sell_queue.pop();\n int x = amount;\n amount -= min(amount, amt);\n amt -= min(x, amt);\n if (amt > 0) {\n sell_queue.push(make_pair(sp, amt));\n break;\n }\n }\n if (amount > 0) {\n buy_queue.push(make_pair(price, amount));\n }\n break;\n //sell\n case 1:\n while(!buy_queue.empty() && buy_queue.top().first >= price && amount > 0) {\n auto [sp, amt] = buy_queue.top();\n buy_queue.pop();\n int x = amount;\n amount -= min(amount, amt);\n amt -= min(x, amt);\n if (amt > 0) {\n buy_queue.push(make_pair(sp, amt));\n break;\n }\n }\n if (amount > 0) {\n sell_queue.push(make_pair(price, amount));\n }\n break;\n }\n }\n int res = 0;\n while(!buy_queue.empty()) { \n auto [p, amt] = buy_queue.top();\n buy_queue.pop();\n res += amt % mod; res %= mod;\n }\n while(!sell_queue.empty()) { \n auto [p, amt] = sell_queue.top();\n sell_queue.pop();\n res += amt % mod; res %= mod;\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | C++ priority_queue solution | c-priority_queue-solution-by-jcodefun-dli8 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | JCodeFun | NORMAL | 2024-07-15T08:48:30.339214+00:00 | 2024-07-15T08:48:30.339236+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\n#include <queue>\n#include <vector>\n#include <algorithm>\n\nusing std::accumulate;\nusing std::vector;\nusing std::priority_queue;\n\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n auto MinHeapFn = [](const pair<int, int> &a, const pair<int, int> &b) {\n return a.first > b.first;\n };\n priority_queue<pair<int, int>> buy; // max heap (default behavior)\n priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(MinHeapFn)> sell; // min heap\n\n auto toBuy = [&buy, &sell](int buyPrice, int buyAmount){\n while(buyAmount > 0 && !sell.empty() && buyPrice >= sell.top().first){\n auto [sellPrice, sellAmount] = sell.top();\n sell.pop();\n int finalAmount = std::min(buyAmount, sellAmount);\n sellAmount -= finalAmount;\n buyAmount -= finalAmount;\n\n if(sellAmount > 0){\n sell.push({sellPrice, sellAmount});\n }\n }\n\n if(buyAmount > 0){\n buy.push({buyPrice, buyAmount});\n }\n };\n\n auto toSell = [&buy, &sell](int sellPrice, int sellAmount){\n while(sellAmount > 0 && !buy.empty() && sellPrice <= buy.top().first){\n auto[buyPrice, buyAmount] = buy.top();\n buy.pop();\n int finalAmount = std::min(sellAmount, buyAmount);\n buyAmount -= finalAmount;\n sellAmount -= finalAmount;\n\n if(buyAmount > 0){\n buy.push({buyPrice, buyAmount});\n }\n }\n\n if(sellAmount > 0){\n sell.push({sellPrice, sellAmount});\n }\n };\n\n for(const auto &order : orders){\n if(order[2]){ // sell 1\n toSell(order[0], order[1]);\n }else{ // buy 0\n toBuy(order[0], order[1]);\n }\n }\n\n size_t res = 0;\n auto sumFn = [&res](auto &que){\n while(!que.empty()){\n res += que.top().second;\n que.pop();\n } \n };\n\n sumFn(buy);\n sumFn(sell);\n\n return res % (int(1e9) + 7);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | two heaps implementation | two-heaps-implementation-by-jcodefun-6vxs | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | JCodeFun | NORMAL | 2024-07-15T07:32:48.651393+00:00 | 2024-07-15T07:32:48.651423+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nimport heapq\nfrom typing import List\n\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n buy = [] # Max heap (using negative prices)\n sell = [] # Min heap\n\n def toBuy(buyPrice: int, buyAmount: int):\n while buyAmount > 0 and sell and sell[0][0] <= -buyPrice:\n sellPrice, sellAmount = heapq.heappop(sell)\n finalAmount = min(buyAmount, sellAmount)\n sellAmount -= finalAmount\n buyAmount -= finalAmount\n if sellAmount > 0:\n heapq.heappush(sell, [sellPrice, sellAmount])\n # Push the remaining buy order into the max heap if not fully matched\n if buyAmount > 0:\n heapq.heappush(buy, [buyPrice, buyAmount])\n\n def toSell(sellPrice: int, sellAmount: int):\n while sellAmount > 0 and buy and sellPrice <= -buy[0][0]:\n buyPrice, buyAmount = heapq.heappop(buy)\n finalAmount = min(sellAmount, buyAmount)\n buyAmount -= finalAmount\n sellAmount -= finalAmount\n if buyAmount > 0:\n heapq.heappush(buy, [buyPrice, buyAmount])\n # Push the remaining sell order into the min heap if not fully matched\n if sellAmount > 0:\n heapq.heappush(sell, [sellPrice, sellAmount])\n\n for price, amount, typ in orders:\n if typ == 0: # Buy order\n toBuy(-price, amount) # Use negative price to simulate max heap\n else: # Sell order\n toSell(price, amount)\n \n # Calculate the total remaining orders in the backlog\n ans = sum(amount for _, amount in buy) \n ans += sum(amount for _, amount in sell)\n return ans % (10**9 + 7)\n\n``` | 0 | 0 | ['Python3'] | 0 |
number-of-orders-in-the-backlog | Using heap | using-heap-by-vmulani-m9yl | Intuition\nWe need to maintain backlog of sellOrders in minimum price order and backlog of buyOrders in maximum price order. This implies the datastructure we u | vmulani | NORMAL | 2024-07-13T13:24:05.727819+00:00 | 2024-07-13T13:24:05.727860+00:00 | 2 | false | # Intuition\nWe need to maintain backlog of sellOrders in minimum price order and backlog of buyOrders in maximum price order. This implies the datastructure we use must maintain records in sorted order and every time an order is executed completely, the next order must take its place. This is a good fit for Heap datastructure.\n\nOnce you figure this out, the logic for executing orders is a straightforward implementation of the requirement.\n\n# Approach\n1. Process orders in a loop\n2. Determine order type\n3. If buy order, keeping looking for sell order in minheap that matches criteria sellOrder.price<=buyOrder.price. If any buyOrders remain, add it to maxheap\n4. If sell order, keep looking for buy order in maxheap that matches criteria buyOrder.price>=sellOrder.price. If any sellOrders remain, add it to minheap\n5. After one pass through the orders, look for remaining orders in minheap and maxheap and compute their amount sum. This sum can easily exceed integer max length so store it in a long\n6. Return the sum%(10^9+7)\n\n\n# Complexity\n- Time complexity:\nO(n^2) - while looping through orders, we may need to trace back the heap to execute an order at every element\n\n- Space complexity:\nO(n) for maintaining heaps\n\n# Code\n```\nclass Order{\n int price;\n int amount;\n}\n\nclass SellOrder extends Order{\n \n}\n\nclass BuyOrder extends Order{\n \n}\n\nclass OrderComparator implements Comparator<Order>{\n public int compare(Order a, Order b)\n {\n return a.price-b.price;\n }\n}\n\nclass Solution {\n PriorityQueue<Order> sellOrders = new PriorityQueue<>(new OrderComparator());\n PriorityQueue<Order> buyOrders = new PriorityQueue<>(Collections.reverseOrder(new OrderComparator()));\n public int getNumberOfBacklogOrders(int[][] orders) {\n for(int[] order: orders){\n boolean isBuyOrder = order[2]==0?true:false;\n if(isBuyOrder){\n Order buyOrder = new BuyOrder();\n buyOrder.price=order[0];\n buyOrder.amount=order[1];\n //execute order\n while(sellOrders.peek()!=null && sellOrders.peek().price<=buyOrder.price){\n Order sellOrder = sellOrders.peek();\n if(buyOrder.amount>sellOrder.amount){\n sellOrders.poll();\n buyOrder.amount -=sellOrder.amount;\n } else if (buyOrder.amount < sellOrder.amount){\n sellOrder.amount-=buyOrder.amount;\n buyOrder.amount=0;\n break;\n } else {\n buyOrder.amount=0;\n sellOrders.poll();\n break;\n }\n }\n //push to backlog\n if(buyOrder.amount>0){\n buyOrders.add(buyOrder);\n }\n }else {\n Order sellOrder = new SellOrder();\n sellOrder.price=order[0];\n sellOrder.amount=order[1];\n //execute order\n while(buyOrders.peek()!=null && buyOrders.peek().price>=sellOrder.price){\n Order buyOrder = buyOrders.peek();\n if(sellOrder.amount>buyOrder.amount){\n buyOrders.poll();\n sellOrder.amount -=buyOrder.amount;\n } else if (sellOrder.amount < buyOrder.amount){\n buyOrder.amount-=sellOrder.amount;\n sellOrder.amount=0;\n break;\n } else {\n sellOrder.amount=0;\n buyOrders.poll();\n break;\n }\n }\n //push to backlog\n if(sellOrder.amount>0){\n sellOrders.add(sellOrder);\n }\n }\n }\n int mod = 1000000007;\n long totalOrders=0;\n while(buyOrders.peek()!=null){\n totalOrders += buyOrders.poll().amount;\n }\n while(sellOrders.peek()!=null){\n totalOrders +=sellOrders.poll().amount;\n }\n return (int)(totalOrders % mod);\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | python min + max heap | python-min-max-heap-by-harrychen1995-pgjd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | harrychen1995 | NORMAL | 2024-06-26T13:49:07.588729+00:00 | 2024-06-26T13:49:07.588750+00:00 | 28 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n\n\n buy_backlog = []\n sell_backlog = []\n\n\n for i in range(len(orders)):\n p, n, t = orders[i]\n if not t:\n while sell_backlog and sell_backlog[0][0] <= p and n:\n if sell_backlog[0][1] <= n:\n n -= sell_backlog[0][1]\n heapq.heappop(sell_backlog)\n else:\n\n sell_backlog[0][1] -=n\n n = 0\n if n:\n heapq.heappush(buy_backlog, [-p, n])\n else:\n while buy_backlog and -buy_backlog[0][0] >= p and n:\n if buy_backlog[0][1] <= n:\n n -= buy_backlog[0][1]\n heapq.heappop(buy_backlog)\n else:\n\n buy_backlog[0][1] -=n\n n = 0\n if n:\n heapq.heappush(sell_backlog, [p, n])\n\n \n return (sum(map(lambda x:x[1], sell_backlog)) + sum(map(lambda x:x[1], buy_backlog))) % (10**9 + 7)\n\n\n\n\n\n\n\n\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Python3'] | 0 |
number-of-orders-in-the-backlog | Simple Approach using Heap | simple-approach-using-heap-by-tesla_arc-7de4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Tesla_Arc | NORMAL | 2024-06-24T14:41:59.551819+00:00 | 2024-06-24T14:41:59.551851+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#pragma GCC optimize("03","Ofast","inline","fast-math","unroll-loops","no-stack-protector","-ffast-math")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native","f16c")\n#define ll long long int\n#define pp pair<ll,ll>\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n priority_queue<pp,vector<pp>,greater<pp>> sellOrder;\n priority_queue<pp> buyOrder;\n \n for(int i=0;i<orders.size();i++)\n {\n ll price= orders[i][0];\n ll amount= orders[i][1];\n ll orderType= orders[i][2];\n\n if(orderType==0) //Buy order -> check sell order\n {\n //checking the first condition -> if sellOrder is not empty and its smallerEqual to Buy\n //we pop from it, till we have the amount>0\n while(amount > 0 && !sellOrder.empty() && sellOrder.top().first <= price)\n {\n auto [sell_price, sell_amount] = sellOrder.top(); sellOrder.pop();\n if(sell_amount > amount)\n {\n sell_amount -= amount;\n amount = 0;\n sellOrder.push({sell_price, sell_amount});\n }\n else\n {\n amount -= sell_amount;\n }\n }\n //once the amount becomes 0 or sellOrder becomes empty\n //or the above condition becomes false\n //fill the buyOrder\n if(amount > 0) buyOrder.push({price, amount});\n }\n else if(orderType==1) //Sell order -> check buy order\n {\n //checking the first condition -> if buyOrder is not empty and its greaterEqual to Sell\n //we pop from it, till we have the amount>0\n while(amount > 0 && !buyOrder.empty() && buyOrder.top().first >= price)\n {\n auto [buy_price, buy_amount] = buyOrder.top(); buyOrder.pop();\n if(buy_amount > amount)\n {\n buy_amount -= amount;\n amount = 0;\n buyOrder.push({buy_price, buy_amount});\n }\n else\n {\n amount -= buy_amount;\n }\n }\n //once the amount becomes 0 or sellOrder becomes empty\n //or the above condition becomes false\n //fill the buyOrder\n if(amount > 0) sellOrder.push({price, amount});\n }\n }\n\n ll buyOrder_backlog_size =0;\n ll sellOrder_backlog_size=0;\n ll mod = 1000000007;\n\n while(!buyOrder.empty())\n {\n buyOrder_backlog_size = (buyOrder_backlog_size + buyOrder.top().second) % mod;\n buyOrder.pop();\n }\n while(!sellOrder.empty())\n {\n sellOrder_backlog_size = (sellOrder_backlog_size + sellOrder.top().second) % mod;\n sellOrder.pop();\n }\n return (buyOrder_backlog_size + sellOrder_backlog_size) % mod; \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | 1801. Number of Orders in the Backlog.cpp | 1801-number-of-orders-in-the-backlogcpp-6l9wj | Code\n\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int, int>> buy; \n priori | 202021ganesh | NORMAL | 2024-06-17T07:50:52.854728+00:00 | 2024-06-17T07:50:52.854749+00:00 | 2 | false | **Code**\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int, int>> buy; \n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> sell; \n for (auto& order : orders) {\n auto price = order[0], qty = order[1], type = order[2]; \n if (type == 0) buy.emplace(price, qty); \n else sell.emplace(price, qty); \n while (size(buy) && size(sell) && buy.top().first >= sell.top().first) {\n auto [bp, bq] = buy.top(); buy.pop(); \n auto [sp, sq] = sell.top(); sell.pop(); \n if (bq > sq) {\n bq -= sq; \n buy.emplace(bp, bq); \n } else if (bq < sq) {\n sq -= bq; \n sell.emplace(sp, sq); \n }\n }\n } \n int ans = 0; \n while (size(buy)) { ans = (ans + buy.top().second) % 1\'000\'000\'007; buy.pop(); }\n while (size(sell)) { ans = (ans + sell.top().second) % 1\'000\'000\'007; sell.pop(); }\n return ans; \n }\n};\n``` | 0 | 0 | ['C'] | 0 |
number-of-orders-in-the-backlog | Production Ready Solution: Min Heap - Max Heap Approach (Python) | production-ready-solution-min-heap-max-h-mziv | Approach\nUse Max Heap to store buy orders\nUse Min Heap to store sell orders\n\neach heap item should store a tuple of (price, amount)\n\n# Complexity\n- Time | adityachandra | NORMAL | 2024-06-11T14:42:15.572704+00:00 | 2024-06-11T14:42:15.572743+00:00 | 4 | false | # Approach\nUse Max Heap to store buy orders\nUse Min Heap to store sell orders\n\neach heap item should store a tuple of (price, amount)\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def __init__(self):\n self.buy_heap = [] # Max-heap (inverted min-heap)\n self.sell_heap = [] # Min-heap\n self.mod = 10**9 + 7\n\n def handleBuyOrder(self, price, amount):\n """Process buy orders by matching with the lowest sell order available.\n\n Args:\n price (int): Price of the buy order.\n amount (int): Amount of the buy order.\n """\n while amount > 0 and self.sell_heap:\n min_sell_price, min_sell_amount = self.sell_heap[0]\n if min_sell_price <= price:\n if min_sell_amount <= amount:\n amount -= min_sell_amount\n heapq.heappop(self.sell_heap)\n else:\n self.sell_heap[0] = (min_sell_price, min_sell_amount - amount)\n amount = 0\n else:\n break\n\n if amount > 0:\n heapq.heappush(self.buy_heap, (-price, amount))\n\n def handleSellOrder(self, price, amount):\n """Process sell orders by matching with the highest buy order available.\n\n Args:\n price (int): Price of the sell order.\n amount (int): Amount of the sell order.\n """\n while amount > 0 and self.buy_heap:\n max_buy_price, max_buy_amount = -self.buy_heap[0][0], self.buy_heap[0][1]\n if max_buy_price >= price:\n if max_buy_amount <= amount:\n amount -= max_buy_amount\n heapq.heappop(self.buy_heap)\n else:\n self.buy_heap[0] = (-max_buy_price, max_buy_amount - amount)\n amount = 0\n else:\n break\n\n if amount > 0:\n heapq.heappush(self.sell_heap, (price, amount))\n\n def getNumberOfBacklogOrders(self, orders):\n """Calculate the total number of backlog orders after processing all incoming orders.\n\n Args:\n orders (List[List[int]]): List of orders, each represented as [price, amount, orderType]\n\n Returns:\n int: Total number of orders remaining in the backlog.\n """\n for price, amount, orderType in orders:\n if orderType == 0:\n self.handleBuyOrder(price, amount)\n elif orderType == 1:\n self.handleSellOrder(price, amount)\n\n backlog_count = (sum(amount for _, amount in self.buy_heap) +\n sum(amount for _, amount in self.sell_heap))\n return backlog_count % self.mod\n``` | 0 | 0 | ['Python'] | 0 |
number-of-orders-in-the-backlog | Easy python solution (priority queue) | easy-python-solution-priority-queue-by-i-yml0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | idoedo | NORMAL | 2024-06-10T06:54:32.598636+00:00 | 2024-06-10T06:54:32.598668+00:00 | 25 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n sell_backlog = []\n buy_backlog = []\n import heapq\n\n for price, amount, order_type in orders:\n if order_type == 0:\n while amount > 0 and (len(sell_backlog) > 0 and price >= sell_backlog[0][0]):\n if sell_backlog[0][1] > amount:\n sell_backlog[0][1] -= amount\n amount = 0\n else:\n amount -= sell_backlog[0][1]\n heapq.heappop(sell_backlog)\n if amount > 0:\n heapq.heappush(buy_backlog, [-price, amount])\n else:\n while amount > 0 and (len(buy_backlog) > 0 and price <= -buy_backlog[0][0]):\n if buy_backlog[0][1] > amount:\n buy_backlog[0][1] -= amount\n amount = 0\n else:\n amount -= buy_backlog[0][1]\n heapq.heappop(buy_backlog)\n \n if amount > 0:\n heapq.heappush(sell_backlog, [price, amount])\n \n res = sum(x[1] for x in buy_backlog) + sum(x[1] for x in sell_backlog)\n return res % (10 ** 9 + 7)\n\n\n \n``` | 0 | 0 | ['Python3'] | 0 |
number-of-orders-in-the-backlog | Two steps. Easy | two-steps-easy-by-vokasik-2b9m | Only 2 steps:\n1. Add an order to one of the heaps: min_heap for sell, max_heap for buy\n2. Process orders in the heaps\n\nclass Solution:\n def getNumberOfB | vokasik | NORMAL | 2024-05-20T09:12:44.086104+00:00 | 2024-05-20T09:12:44.086136+00:00 | 21 | false | Only 2 steps:\n1. Add an order to one of the heaps: min_heap for sell, max_heap for buy\n2. Process orders in the heaps\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n min_sell = [] # buy: smallest sell <= buy\n max_buy = [] # sell: biggest buy >= sell\n for price, amount, order_type in orders:\n if order_type == 0:\n heappush(max_buy, [-price, amount])\n else:\n heappush(min_sell, [price, amount])\n while min_sell and max_buy and min_sell[0][0] <= -max_buy[0][0]:\n count = min(min_sell[0][1], max_buy[0][1])\n min_sell[0][1] -= count\n max_buy[0][1] -= count\n if min_sell[0][1] == 0:\n heappop(min_sell)\n if max_buy[0][1] == 0:\n heappop(max_buy)\n return (sum(c for _,c in min_sell) + sum(c for _,c in max_buy)) % (10 ** 9 + 7)\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Python', 'Python3'] | 0 |
number-of-orders-in-the-backlog | easy approach!! Just a bit of priority queue knowledge and its really easy | easy-approach-just-a-bit-of-priority-que-q8p8 | Intuition\n Describe your first thoughts on how to solve this problem. \nI am a stock market guy. So appeared easy for me to understand. Just try to understand | gaurav_17_18 | NORMAL | 2024-05-18T04:25:23.706387+00:00 | 2024-05-18T04:25:23.706411+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI am a stock market guy. So appeared easy for me to understand. Just try to understand the problem statement and it will be a matter of minutes to solve this.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nyou can understand the approach by seeing code itself as it is commented and try to take a few of test cases.\n# Complexity\n- Time complexity: O(nlogn) because we are traversing orders once that gives O(n) and Insertion and Deletion happens at most once each for each order. So that takes logarithmic time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int, int>> buy; // Max-Heap for buy orders\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> sell; // Min-Heap for sell orders\n \n for (auto& order : orders) {\n int price = order[0];\n int quantity = order[1];\n int type = order[2];\n \n if (type == 0) {\n // This is a buy order\n while (!sell.empty() && sell.top().first <= price && quantity > 0) {\n auto [sellPrice, sellQuantity] = sell.top();\n sell.pop();\n if (sellQuantity > quantity) {\n sellQuantity -= quantity;\n quantity = 0;\n sell.push({sellPrice, sellQuantity});\n } else {\n quantity -= sellQuantity;\n }\n }\n if (quantity > 0) {\n buy.push({price, quantity});\n }\n } else {\n // This is a sell order\n while (!buy.empty() && buy.top().first >= price && quantity > 0) {\n auto [buyPrice, buyQuantity] = buy.top();\n buy.pop();\n if (buyQuantity > quantity) {\n buyQuantity -= quantity;\n quantity = 0;\n buy.push({buyPrice, buyQuantity});\n } else {\n quantity -= buyQuantity;\n }\n }\n if (quantity > 0) {\n sell.push({price, quantity});\n }\n }\n }\n \n long long backlog = 0;\n long long modulo = 1e9 + 7;\n \n while (!buy.empty()) {\n backlog = (backlog + buy.top().second) % modulo;\n buy.pop();\n }\n \n while (!sell.empty()) {\n backlog = (backlog + sell.top().second) % modulo;\n sell.pop();\n }\n \n return backlog;\n }\n}; | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | [C++] 2 Approaches, Max-Heap (Bids) and Min-Heap (Asks), Level 2 Quotes Processing | c-2-approaches-max-heap-bids-and-min-hea-enzn | Complexity\n- Time complexity: O(nlogn)\n- Space complexity: O(n)\n\n# Code\n## Approach 1 (First Push to Heap, then Match)\n\nclass Solution {\npublic:\n in | amanmehara | NORMAL | 2024-05-17T04:31:27.832711+00:00 | 2024-05-17T04:49:24.228948+00:00 | 6 | false | # Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n## Approach 1 (First Push to Heap, then Match)\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int, int>> bids;\n priority_queue<pair<int, int>> asks;\n long backlog = 0;\n for (const auto& order : orders) {\n backlog += order[1];\n if (order[2] == 0) {\n bids.emplace(order[0], order[1]);\n } else {\n asks.emplace(-order[0], order[1]);\n }\n while (!bids.empty() && !asks.empty()) {\n auto [bid_pri, bid_qty] = bids.top();\n auto [ask_pri, ask_qty] = asks.top();\n if (bid_pri >= -ask_pri) {\n bids.pop();\n asks.pop();\n int match = min(bid_qty, ask_qty);\n backlog -= (2 * match);\n if (bid_qty > match) {\n bids.emplace(bid_pri, bid_qty - match);\n }\n if (ask_qty > match) {\n asks.emplace(ask_pri, ask_qty - match);\n }\n } else {\n break;\n }\n }\n }\n int mod = 1e9 + 7;\n return backlog % mod;\n }\n};\n```\n## Approach 2 (First Match, then Push to Heap)\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int, int>> bids;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> asks;\n for (const auto& order : orders) {\n if (order[2] == 0) {\n int qty = order[1];\n while (!asks.empty() && qty > 0 && asks.top().first <= order[0]) {\n auto [ask_pri, ask_qty] = asks.top();\n asks.pop();\n if (qty - ask_qty >= 0) {\n qty -= ask_qty;\n } else {\n asks.emplace(ask_pri, ask_qty - qty);\n qty = 0;\n }\n }\n if (qty > 0) {\n bids.emplace(order[0], qty);\n }\n } else {\n int qty = order[1];\n while (!bids.empty() && qty > 0 && bids.top().first >= order[0]) {\n auto [bid_pri, bid_qty] = bids.top();\n bids.pop();\n if (qty - bid_qty >= 0) {\n qty -= bid_qty;\n } else {\n bids.emplace(bid_pri, bid_qty - qty);\n qty = 0;\n }\n }\n if (qty > 0) {\n asks.emplace(order[0], qty);\n }\n }\n }\n int mod = 1e9 + 7;\n long backlog = 0;\n while (!bids.empty()) {\n auto [_, bid_qty] = bids.top();\n backlog = (backlog + bid_qty) % mod;\n bids.pop();\n }\n while (!asks.empty()) {\n auto [_, ask_qty] = asks.top();\n backlog = (backlog + ask_qty) % mod;\n asks.pop();\n }\n return backlog;\n }\n};\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
number-of-orders-in-the-backlog | N Log N + clean code | n-log-n-clean-code-by-gautii0911-bv5k | \n\n# Code\n\nimport java.util.PriorityQueue;\n\nclass Solution {\n\n // Nested class representing a buy order\n public class Buy {\n int price;\n | gautii0911 | NORMAL | 2024-05-11T16:57:23.271408+00:00 | 2024-05-11T16:57:23.271429+00:00 | 7 | false | \n\n# Code\n```\nimport java.util.PriorityQueue;\n\nclass Solution {\n\n // Nested class representing a buy order\n public class Buy {\n int price;\n int amount;\n\n public Buy(int p, int a) {\n price = p;\n amount = a;\n }\n }\n\n // Nested class representing a sell order\n public class Sell {\n int price;\n int amount;\n\n public Sell(int p, int a) {\n price = p;\n amount = a;\n }\n }\n\n // Priority queues for buy and sell orders\n PriorityQueue<Buy> buy;\n PriorityQueue<Sell> sell;\n\n // Method to get the number of backlog orders\n public int getNumberOfBacklogOrders(int[][] orders) {\n // Initialize priority queues\n buy = new PriorityQueue<>((a, b) -> b.price - a.price); // Max heap for buy orders\n sell = new PriorityQueue<>((a, b) -> a.price - b.price); // Min heap for sell orders\n\n int mod = 1000000007; // Modulus value\n int ans = 0; // Accumulator for total orders\n\n // Process each order\n for (int[] o : orders) {\n int amount = o[1];\n int price = o[0];\n int type = o[2];\n\n if (type == 0) {\n buying(amount, price);\n } else {\n selling(amount, price);\n }\n }\n\n // Sum up remaining orders\n while (!buy.isEmpty()) {\n ans = (ans + buy.poll().amount) % mod;\n }\n\n while (!sell.isEmpty()) {\n ans = (ans + sell.poll().amount) % mod;\n }\n\n return ans;\n }\n\n // Method to process buy orders\n public void buying(int amount, int price) {\n while (!sell.isEmpty() && amount > 0 && sell.peek().price <= price) {\n Sell currSell = sell.poll();\n int quantity = amount - Math.min(currSell.amount, amount);\n if (quantity == 0) {\n currSell.amount -= amount;\n sell.offer(currSell);\n }\n amount = quantity;\n }\n\n if (amount != 0) {\n buy.offer(new Buy(price, amount));\n }\n }\n\n // Method to process sell orders\n public void selling(int amount, int price) {\n while (!buy.isEmpty() && amount > 0 && buy.peek().price >= price) {\n Buy currBuy = buy.poll();\n int quantity = amount - Math.min(currBuy.amount, amount);\n if (quantity == 0) {\n currBuy.amount -= amount;\n buy.offer(currBuy);\n }\n amount = quantity;\n }\n\n if (amount != 0) {\n sell.offer(new Sell(price, amount));\n }\n }\n}\n\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | Using Priority Queue | using-priority-queue-by-usernamectrlc-icop | Intuition\n Describe your first thoughts on how to solve this problem. \nImplement two priority queues to manage orders: one for buy orders sorted in descending | usernamectrlc | NORMAL | 2024-04-16T01:07:26.639303+00:00 | 2024-04-16T01:07:26.639323+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImplement two priority queues to manage orders: one for buy orders sorted in descending order and another for sell orders sorted in ascending order. When both buy and sell conditions are satisfied, begin removing the order from the respective priority queue.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private val MODULO = 1_000_000_007\n fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int {\n val buy = PriorityQueue<IntArray>(compareBy {-it[0]})\n val sell = PriorityQueue<IntArray>(compareBy {it[0]})\n\n orders.forEach{\n if(it[2] == 0){\n if(sell.isEmpty()) buy.offer(it)\n else{\n if (it[0] >= sell.peek()[0]){\n var quantities = it[1]\n while( quantities > 0 && sell.isNotEmpty() && it[0] >= sell.peek()[0]){\n val sellOrder = sell.poll()\n if( quantities < sellOrder[1]){\n sell.offer(intArrayOf(sellOrder[0], sellOrder[1] - quantities, sellOrder[2]))\n quantities = 0\n } else{\n quantities -= sellOrder[1]\n }\n }\n if( quantities > 0) buy.offer(intArrayOf(it[0], quantities, it[2]))\n } else buy.offer(it)\n }\n } else{\n if( buy.isEmpty()) sell.offer(it)\n else{\n if(it[0] <= buy.peek()[0]){\n var quantities = it[1]\n while( quantities > 0 && buy.isNotEmpty() && it[0] <= buy.peek()[0]){\n val buyOrder = buy.poll()\n if( quantities < buyOrder[1]){\n buy.offer(intArrayOf(buyOrder[0], buyOrder[1] - quantities, buyOrder[2]))\n quantities = 0\n } else quantities -= buyOrder[1]\n }\n if(quantities > 0) sell.offer(intArrayOf(it[0], quantities, it[2]))\n\n\n } \n else {\n sell.offer(it)\n } \n\n }\n\n\n }\n\n\n\n }\n\n var res = 0 \n\n while(buy.isNotEmpty()){\n res += buy.poll()[1]\n res %= MODULO\n }\n\n while(sell.isNotEmpty()){\n res += sell.poll()[1]\n res %= MODULO\n }\n\n return res\n }\n\n}\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Kotlin'] | 0 |
number-of-orders-in-the-backlog | two priority queue | two-priority-queue-by-iazinschi2005-rvef | \n# Code\n\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int,int>> buyOrders;\n | iazinschi2005 | NORMAL | 2024-03-29T23:13:06.257334+00:00 | 2024-03-29T23:13:06.257394+00:00 | 7 | false | \n# Code\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n priority_queue<pair<int,int>> buyOrders;\n priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> sellOrders;\n int diff;\n for(auto&x:orders){\n if(x[2]==0) buyOrders.push({x[0], x[1]});\n else sellOrders.push({x[0], x[1]});\n\n while(!buyOrders.empty() && !sellOrders.empty() && buyOrders.top().first>=sellOrders.top().first){\n auto buyStock=buyOrders.top();\n auto sellStock=sellOrders.top();\n buyOrders.pop();sellOrders.pop();\n diff = buyStock.second-sellStock.second;\n if(diff<0){\n sellOrders.push({sellStock.first, abs(diff)});\n } else if(diff>0){\n buyOrders.push({buyStock.first, diff});\n }\n }\n }\n\n int res=0, mod=1e9+7;\n while(!buyOrders.empty()){\n res = (res+buyOrders.top().second)%mod;\n buyOrders.pop();\n }\n while(!sellOrders.empty()){\n res = (res+sellOrders.top().second)%mod;\n sellOrders.pop();\n }\n return res;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
number-of-orders-in-the-backlog | Java | Priority Queue | java-priority-queue-by-baljitdhanjal-mxfo | \n\n# Code\n\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> | baljitdhanjal | NORMAL | 2024-03-18T07:20:20.106542+00:00 | 2024-03-18T07:20:20.106577+00:00 | 15 | false | \n\n# Code\n```\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);\n PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n long mod = 1000000007;\n int res = 0;\n\n for (int[] order : orders) {\n if (order[2] == 0) {\n while (!minHeap.isEmpty()\n && minHeap.peek()[0] <= order[0]\n && order[1] > 0) {\n int min = Math.min(minHeap.peek()[1], order[1]);\n order[1] -= min;\n minHeap.peek()[1] -= min;\n if (minHeap.peek()[1] == 0)\n minHeap.poll();\n }\n\n if (order[1] > 0) {\n maxHeap.offer(new int[] { order[0], order[1] });\n }\n } else {\n while (!maxHeap.isEmpty()\n && maxHeap.peek()[0] >= order[0]\n && order[1] > 0) {\n int min = Math.min(maxHeap.peek()[1], order[1]);\n order[1] -= min;\n maxHeap.peek()[1] -= min;\n if (maxHeap.peek()[1] == 0)\n maxHeap.poll();\n }\n\n if (order[1] > 0) {\n minHeap.offer(new int[] { order[0], order[1] });\n }\n }\n }\n\n while (!minHeap.isEmpty()) {\n res += minHeap.poll()[1];\n res %= mod;\n }\n\n while (!maxHeap.isEmpty()) {\n res += maxHeap.poll()[1];\n res %= mod;\n }\n\n return res;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | 1801. Number of Orders in the Backlog - Beats 86 % | 1801-number-of-orders-in-the-backlog-bea-ie8o | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | jaisalShah | NORMAL | 2024-03-09T06:58:56.659072+00:00 | 2024-03-09T06:58:56.659109+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom heapq import heapify, heappop, heappush\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n bq = [] # contains (-price, amount), maxHeap\n sq = [] # contains (price, amount), minHeap\n heapify(bq)\n heapify(sq)\n for [price, amount, oType] in orders:\n if oType == 0:\n # check if sq exists, amount > 0 and seller with less than price exists\n while len(sq) > 0 and sq[0][0] <= price and amount > 0:\n [existingPrice, existingAmount] = heappop(sq)\n reaminingAmount = existingAmount - amount\n amount = amount - existingAmount\n # if seller still exists after fulfilling order then add the remaing to sell queue\n if(reaminingAmount) > 0:\n heappush(sq, (existingPrice, reaminingAmount))\n # if no sq or no seller for price or incomplete order then add backlog in buy queue\n if amount > 0:\n heappush(bq, (-price, amount))\n else:\n # check if bq exists, amount > 0 and buyer with greater than price exists\n while len(bq) > 0 and -bq[0][0] >= price and amount > 0:\n [existingPrice, existingAmount] = heappop(bq)\n reaminingAmount = existingAmount - amount\n amount = amount - existingAmount\n # if buyer still exists after fulfilling order then add the remaining to buy queue\n if(reaminingAmount) > 0:\n heappush(bq, (existingPrice, reaminingAmount))\n # if no bq or no buyer for price or incomplete order then add backlog in sell queue\n if amount > 0:\n heappush(sq, (price, amount))\n res = 0\n while len(sq) > 0:\n res += heappop(sq)[1]\n while len(bq) > 0:\n res += heappop(bq)[1]\n return res % (10 ** 9 + 7)\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Python3'] | 0 |
number-of-orders-in-the-backlog | Followable Java Code | PriorityQueue | Custom Order class | followable-java-code-priorityqueue-custo-d6x0 | Intuition\nHeapify the input orders. As you add them to your buy and sell prioirty queues, see if you can make a trade. \n\nPS: The Order class basically helps | mehulsri95 | NORMAL | 2024-03-07T01:56:40.052966+00:00 | 2024-03-07T01:56:40.052996+00:00 | 12 | false | # Intuition\nHeapify the input orders. As you add them to your buy and sell prioirty queues, see if you can make a trade. \n\nPS: The Order class basically helps to follow along and avoid messy code (demonstrates a little OOP too :P) \n\n# Approach\nUncomment all Sop\'s to follow along. Hope this helps!\n\n# Code\n```\nclass Order {\n int price;\n int amount;\n Order(int p, int a) {\n this.price = p;\n this.amount = a;\n }\n}\n\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n Queue<Order> buyQ = new PriorityQueue<Order>((o1, o2) -> (Integer.compare(o2.price, o1.price)));\n Queue<Order> sellQ = new PriorityQueue<Order>((o1, o2) -> (Integer.compare(o1.price, o2.price)));\n \n // int i=1;\n for (int[] order : orders) {\n int priceI = order[0];\n int amountI = order[1];\n int typeI = order[2];\n Order o = new Order(priceI, amountI);\n if (typeI == 0) { // buy\n buyQ.add(o);\n } else if (typeI == 1) { // sell\n sellQ.add(o);\n }\n\n // System.out.println("Starting processing order " + i);\n processOrder(buyQ, sellQ);\n // System.out.println("Ending processing order " + i+"\\n\\n");\n // i +=1;\n \n }\n int retval = 0;\n for (Order o : buyQ) {\n retval += o.amount;\n retval %= Math.pow(10,9) + 7;\n // System.out.println(retval);\n }\n for (Order o : sellQ) {\n retval += o.amount;\n retval %= Math.pow(10,9) + 7;\n // System.out.println(retval);\n }\n \n // retval %= Math.pow(10,9) + 7;\n return retval;\n }\n\n private void processOrder(Queue<Order> b, Queue<Order> s) {\n // System.out.format("Buy size %d, sell size %d\\n", b.size(), s.size());\n \n if (b.size() == 0 || s.size() == 0) return;\n Order bOrder = b.peek();\n Order sOrder = s.peek();\n if (sOrder.price <= bOrder.price) {\n // System.out.println("Trade happening");\n if (bOrder.amount <= sOrder.amount) {\n // System.out.format("Selling %d orders at price %d from %d orders\\n", bOrder.amount, sOrder.price, sOrder.amount);\n b.poll();\n sOrder.amount -= bOrder.amount;\n } else {\n // System.out.format("Selling %d orders at price %d from %d orders\\n", sOrder.amount, sOrder.price, bOrder.amount);\n s.poll();\n bOrder.amount -= sOrder.amount;\n }\n processOrder(b, s);\n }\n }\n}\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Java'] | 0 |
number-of-orders-in-the-backlog | two heaps | two-heaps-by-maxorgus-e0zp | \n\n# Code\n\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n bidbook = []\n askbook = []\n for | MaxOrgus | NORMAL | 2024-02-07T01:33:49.687209+00:00 | 2024-02-07T01:33:49.687231+00:00 | 15 | false | \n\n# Code\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n bidbook = []\n askbook = []\n for price,amount,otype in orders:\n if otype == 0:\n while amount and askbook and askbook[0][0]<=price:\n askp,asks = heapq.heappop(askbook)\n if amount >= asks:\n amount -= asks\n else:\n asks -= amount\n amount = 0\n heapq.heappush(askbook,(askp,asks))\n if amount:\n heapq.heappush(bidbook,(-price,amount))\n else:\n while amount and bidbook and -bidbook[0][0]>=price:\n bidp,bids = heapq.heappop(bidbook)\n if amount >= bids:\n amount -= bids\n else:\n bids -= amount\n amount = 0\n heapq.heappush(bidbook,(bidp,bids))\n if amount:\n heapq.heappush(askbook,(price,amount))\n res = 0\n for p,m in bidbook:\n res += m\n for p,m in askbook:\n res += m\n return res % (10**9+7)\n \n\n\n \n\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Python3'] | 0 |
number-of-orders-in-the-backlog | [Java] ✅ 22ms ✅ 99% ✅ Priority Queue ✅ CLEAN CODE | java-22ms-99-priority-queue-clean-code-b-p95z | Approach\n1. Use 2 queues of type int[]. \n - buyQueue, sorting in descending order of price\n - sellQueue, sorting in ascending order of price\n2. Proces | StefanelStan | NORMAL | 2024-01-23T00:28:18.112235+00:00 | 2024-01-23T00:28:18.112264+00:00 | 66 | false | # Approach\n1. Use 2 queues of type int[]. \n - buyQueue, sorting in descending order of price\n - sellQueue, sorting in ascending order of price\n2. Process each order by type:\n3. BUY, you need to look in sellQueue, \n - loop while order\'s price >= head of queue price. \n - Keep track of what you take out from sellQueue. \n - Also, if the order ammount is still > 0, put it in the sellQueue\n4. SELL: you need to look in buyQueue;\n - loop while queue is not empty and order price <= head of queue price\n - Keep track of what you take out from buyQueue. If current head queue.amount == 0, remove from queue.\n - At the end, if order\'s amount > 0, put it in the sellQueue\n5. For each step, you will have a delta (diff between what goes out from lookInqueue what goes in putInQueue)\n - Add these deltas and return their modulo sum.\n\n# Complexity\n- Time complexity:$$O(n * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n PriorityQueue<int[]> buyQueue = new PriorityQueue<>((a,b) -> Integer.compare(b[0], a[0]));\n PriorityQueue<int[]> sellQueue = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));\n long backlogStatus = 0L;\n for (int[] order : orders) {\n if (order[2] == 0) { //BUY\n backlogStatus += processItem(order, sellQueue, buyQueue, 0);\n } else { // SELL\n backlogStatus += processItem(order, buyQueue, sellQueue, 1);\n }\n }\n return (int)(backlogStatus % 1_000_000_007);\n }\n private int processItem(int[] order, PriorityQueue<int[]> lookInQueue, PriorityQueue<int[]> putInQueue, int op) {\n if (lookInQueue.isEmpty() || !(op == 0 ? order[0] >= lookInQueue.peek()[0] : order[0] <= lookInQueue.peek()[0])) {\n putInQueue.add(order);\n return order[1];\n }\n int backlogDelta = 0;\n while (!lookInQueue.isEmpty() && order[1] > 0 && (op == 0 ? order[0] >= lookInQueue.peek()[0] : order[0] <= lookInQueue.peek()[0])) {\n int amountToRemove = Math.min(lookInQueue.peek()[1], order[1]);\n backlogDelta += -amountToRemove;\n order[1] -= amountToRemove;\n lookInQueue.peek()[1] -= amountToRemove;\n if (lookInQueue.peek()[1] == 0) {\n lookInQueue.poll();\n }\n }\n if (order[1] > 0) {\n backlogDelta += order[1];\n putInQueue.add(order);\n }\n return backlogDelta;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | C++||clean and explained||using heap | cclean-and-explainedusing-heap-by-mr_err-pj8d | Intuition\nThe intuition behind the provided code lies in its implementation of a basic trading algorithm that handles buy and sell orders efficiently. The algo | mr_Error_404 | NORMAL | 2024-01-14T12:01:04.524226+00:00 | 2024-01-14T12:01:04.524256+00:00 | 9 | false | # Intuition\nThe intuition behind the provided code lies in its implementation of a basic trading algorithm that handles buy and sell orders efficiently. The algorithm uses two priority queues, one for buy orders and one for sell orders, to maintain a sorted order by price. As it iterates through each order in the input vector, it categorizes the order as a buy or sell order based on the type. For buy orders, the algorithm attempts to fulfill them by matching with existing sell orders, adjusting quantities accordingly. Similarly, for sell orders, it seeks matching buy orders. The process ensures that orders are processed in a way that maximizes fulfillment while maintaining sorted queues. The final step involves calculating the total backlogged orders by summing the remaining quantities in both the buy and sell priority queues. The algorithm optimally manages the order book, providing insights into the backlog of unfulfilled orders in a trading environment.\n\n# Approach\nThe approach of the given code is to simulate a trading system and efficiently handle buy and sell orders. Here\'s a step-by-step breakdown of the approach:\n - **Data Structures:**\n Two priority queues (buyOrders and sellOrders) are used to maintain the buy and sell orders sorted by price.\nThe min-heap property is applied to sellOrders so that the lowest price sell order is at the front.\nThe max-heap property is applied to buyOrders so that the highest price buy order is at the front.\nIterating Through Orders:\nThe code iterates through each order in the input vector, extracting relevant information such as price, quantity, and order type (buy or sell).\n- **Processing Buy Orders:**\n For buy orders, the algorithm attempts to match them with existing sell orders.\nIt iterates through the sell orders while there is quantity to be fulfilled in the buy order.\nIf a matching sell order is found (lower or equal price), it adjusts quantities accordingly and updates the sell queue.\nIf the buy order cannot be fulfilled by the existing sell orders, it is added to the buy queue.\n- **Processing Sell Orders:**\nFor sell orders, the algorithm seeks matching buy orders following a similar process as with buy orders.\nIt iterates through the buy orders while there is quantity to be fulfilled in the sell order.\nIf a matching buy order is found (higher or equal price), it adjusts quantities accordingly and updates the buy queue.\nIf the sell order cannot be fulfilled by the existing buy orders, it is added to the sell queue.\n- **Calculating Total Backlogs:**\nAfter processing all orders, the code calculates the total backlogged orders by summing the remaining quantities in both the buy and sell priority queues.\n- **Result:**\nThe final result is the total number of backlogged orders, considering a modulo operation for numerical stability.\nOverall, the approach efficiently manages and processes orders, ensuring that buy and sell orders are matched appropriately while maintaining sorted queues based on price. This algorithm provides a practical simulation of a trading system\'s order book.\n\n# Complexity\n- Time complexity:\nO(n * log(k)).\n\n- Space complexity:\nO(n).\n\n# Code\n```\nclass Solution {\npublic:\n int getNumberOfBacklogOrders(vector<vector<int>>& orders) \n {\n // Priority queue for sell orders, sorted by price (min heap)\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> sellOrders;\n // Priority queue for buy orders, sorted by price (max heap)\n priority_queue<pair<int, int>> buyOrders;\n // Loop through each order in the input vector\n for (const auto& order : orders)\n {\n // Extract order details\n int orderPrice = order[0];\n int orderQuantity = order[1];\n int orderType = order[2]; // Assuming type is at index 2 in the inner vector\n // Process buy orders\n if (orderType == 0)\n {\n // If no sell orders, add the buy order to buy queue and continue to the next order\n if (sellOrders.empty())\n {\n buyOrders.push({orderPrice, orderQuantity});\n continue;\n }\n // Process buy order against sell orders\n while (!sellOrders.empty() && orderQuantity > 0)\n {\n int sellPrice = sellOrders.top().first;\n int sellQuantity = sellOrders.top().second;\n // Check if the sell order can be completely fulfilled\n if (sellPrice <= orderPrice)\n {\n sellOrders.pop();\n if (sellQuantity >= orderQuantity)\n {\n sellQuantity -= orderQuantity;\n orderQuantity = 0;\n // If there is remaining sell quantity, add it back to sell orders\n if (sellQuantity > 0) \n {\n sellOrders.push({sellPrice, sellQuantity});\n }\n } \n else {\n orderQuantity -= sellQuantity;\n }\n } \n else \n {\n // If the current sell order has a higher price, add the buy order to buy queue\n buyOrders.push({orderPrice, orderQuantity});\n orderQuantity = 0;\n break;\n }\n }\n // If there is remaining quantity for the buy order, add it to buy queue\n if (orderQuantity > 0)\n {\n buyOrders.push({orderPrice, orderQuantity});\n }\n } \n else \n { // Process sell orders\n // If no buy orders, add the sell order to sell queue and continue to the next order\n if (buyOrders.empty())\n {\n sellOrders.push({orderPrice, orderQuantity});\n continue;\n }\n // Process sell order against buy orders\n while (!buyOrders.empty() && orderQuantity > 0) \n {\n int buyPrice = buyOrders.top().first;\n int buyQuantity = buyOrders.top().second;\n\n // Check if the buy order can be completely fulfilled\n if (buyPrice >= orderPrice) \n {\n buyOrders.pop();\n\n if (buyQuantity >= orderQuantity)\n {\n buyQuantity -= orderQuantity;\n orderQuantity = 0;\n // If there is remaining buy quantity, add it back to buy orders\n if (buyQuantity > 0) \n {\n buyOrders.push({buyPrice, buyQuantity});\n }\n } \n else\n {\n orderQuantity -= buyQuantity;\n }\n } \n else\n {\n // If the current buy order has a lower price, add the sell order to sell queue\n sellOrders.push({orderPrice, orderQuantity});\n orderQuantity = 0;\n break;\n }\n }\n // If there is remaining quantity for the sell order, add it to sell queue\n if (orderQuantity > 0) \n {\n sellOrders.push({orderPrice, orderQuantity});\n }\n }\n }\n // Calculate the total backlogs from remaining sell and buy orders\n int totalBacklogs = 0;\n const int mod = 1e9 + 7;\n while (!sellOrders.empty()) \n {\n totalBacklogs = (totalBacklogs + sellOrders.top().second) % mod;\n sellOrders.pop();\n }\n while (!buyOrders.empty())\n {\n totalBacklogs = (totalBacklogs + buyOrders.top().second) % mod;\n buyOrders.pop();\n }\n // Return the final result\n return totalBacklogs;\n }\n};\n\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Simulation', 'C++'] | 0 |
number-of-orders-in-the-backlog | 1801. beginner friendly | 1801-beginner-friendly-by-xze1932-6z7r | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | xze1932 | NORMAL | 2024-01-14T05:01:40.351136+00:00 | 2024-01-14T05:01:40.351167+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nlogn)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution(object):\n def getNumberOfBacklogOrders(self, orders):\n """\n :type orders: List[List[int]]\n :rtype: int\n """\n buy = []\n sell = []\n for i in orders:\n if i[2] == 0:\n tp = i[1] # if buy vlaues\n while sell:\n k, v = heapq.heappop(sell)\n if k <= i[0]: \n if v < tp:\n tp -= v\n else:\n v -= tp\n tp = 0\n # make tp = 0 to represent no current key left\n heapq.heappush(sell, (k, v))\n break\n else: \n # if no values in sell smaller than current value\n heapq.heappush(sell, (k, v))\n heapq.heappush(buy, (-i[0], tp))\n # store minus i[0] as the minimum number\n tp = 0 \n # make tp = 0 to represent no current key left\n break\n if tp: # if sell is empty but still buy values \n heapq.heappush(buy, (-i[0], tp))\n \n elif i[2] == 1: # if sell values\n tp = i[1]\n while buy:\n k, v = heapq.heappop(buy)\n if -k >= i[0]: \n if v < tp:\n tp -= v\n else:\n v -= tp\n tp = 0\n heapq.heappush(buy, (k, v))\n break\n else: \n heapq.heappush(buy, (k, v))\n heapq.heappush(sell, (i[0], tp))\n tp = 0\n break\n if tp:\n heapq.heappush(sell, (i[0], tp))\n \n ans = 0 \n # add all left counts\n for i in buy:\n ans += i[1]\n for i in sell:\n ans += i[1]\n return ans % (10 ** 9 + 7)\n``` | 0 | 0 | ['Python'] | 0 |
number-of-orders-in-the-backlog | Java O(NlogN) | java-onlogn-by-tbekpro-c884 | Complexity\n- Time complexity: O(NlogN)\n\n# Code\n\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n PriorityQueue<Order> p | tbekpro | NORMAL | 2024-01-13T15:18:57.648531+00:00 | 2024-01-13T15:18:57.648560+00:00 | 3 | false | # Complexity\n- Time complexity: O(NlogN)\n\n# Code\n```\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n PriorityQueue<Order> pqb = new PriorityQueue<>((a, b) -> b.price - a.price);\n PriorityQueue<Order> pqs = new PriorityQueue<>((a, b) -> a.price - b.price);\n \n for (int[] o: orders) {\n Order curr = new Order(o[0], o[1]);\n \n if (o[2] == 0) {\n //buy\n while (!pqs.isEmpty()) {\n Order s = pqs.poll();\n if (curr.price >= s.price) {\n int diff = curr.amount - s.amount;\n if (diff > 0) {\n curr.amount = diff;\n } else {\n s.amount -= curr.amount;\n pqs.offer(s);\n curr.amount = 0;\n break;\n }\n } else {\n pqs.offer(s);\n break;\n }\n }\n if (curr.amount > 0) pqb.offer(curr);\n } else {\n //sell\n while (!pqb.isEmpty()) {\n Order b = pqb.poll();\n if (b.price >= curr.price) {\n int diff = curr.amount - b.amount;\n if (diff > 0) {\n curr.amount = diff;\n } else {\n b.amount -= curr.amount;\n pqb.offer(b);\n curr.amount = 0;\n break;\n }\n } else {\n pqb.offer(b);\n break;\n }\n }\n if (curr.amount > 0) pqs.offer(curr);\n }\n }\n\n long sum = 0L;\n while (!pqs.isEmpty()) {\n sum += pqs.poll().amount;\n }\n\n while (!pqb.isEmpty()) {\n sum += pqb.poll().amount;\n }\n\n return (int)(sum % 1_000_000_007L);\n }\n}\n\nclass Order {\n int price, amount;\n\n public Order(int p, int a) {\n price = p;\n amount = a;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | Java Priority Queue with comments | java-priority-queue-with-comments-by-bru-egav | \nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n // create a max heap for buy orders sorted by price\n // When we p | bruce-decker | NORMAL | 2024-01-08T01:58:58.786936+00:00 | 2024-01-08T02:55:10.259706+00:00 | 4 | false | ```\nclass Solution {\n public int getNumberOfBacklogOrders(int[][] orders) {\n // create a max heap for buy orders sorted by price\n // When we peak buy orders, we will get the largest price in buyOrders without removing it\n PriorityQueue<int []> buyOrders = new PriorityQueue<>((a, b) -> b[0] - a[0]);\n // create a min heap for sell orders sorted by price\n // When we peak sellOrders, we will get the smallest price in sellOrders without removing it\n PriorityQueue<int []> sellOrders = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n for (int [] order : orders) {\n int price = order[0];\n int amount = order[1];\n int orderType = order[2];\n if (orderType == 0) {\n // buying power must be greater than or equal to selling price\n // Hence, price >= sellOrders.peek()[0]\n // added amount > 0 in the condition to avoid infinite loop \n while (!sellOrders.isEmpty() && price >= sellOrders.peek()[0] && amount > 0) {\n // \n if (amount >= sellOrders.peek()[1]) {\n amount -= sellOrders.peek()[1];\n sellOrders.poll();\n } else {\n sellOrders.peek()[1] -= amount;\n amount = 0;\n }\n \n }\n // if the amount is a positive number, add the order to buyOrders PriorityQueue\n if (amount > 0) {\n buyOrders.add(new int [] {price, amount});\n }\n } else {\n // Same thing there. Buying power must be greater than or equal to selling price\n // Hence, price <= buyOrders.peek()[0] since the orderType is 1 (sell order) here\n while (!buyOrders.isEmpty() && price <= buyOrders.peek()[0] && amount > 0) {\n if (amount >= buyOrders.peek()[1]) {\n amount -= buyOrders.peek()[1];\n buyOrders.poll();\n } else {\n buyOrders.peek()[1] -= amount;\n // set amount to zero after substracting \n amount = 0;\n }\n \n }\n // if the amount is a positive number, add the order to sellOrders PriorityQueue\n if (amount > 0) {\n sellOrders.add(new int [] {price, amount});\n }\n }\n }\n \n long sum = 0;\n int mod = 1_000_000_007;\n // ensure the sum stays withint the int range\n while (!buyOrders.isEmpty()) {\n sum = (sum + buyOrders.poll()[1]) % mod;\n }\n while (!sellOrders.isEmpty()) {\n sum = (sum + sellOrders.poll()[1]) % mod;\n }\n\n \n return (int) sum;\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
number-of-orders-in-the-backlog | [JavaScript] 1801. Number of Orders in the Backlog | javascript-1801-number-of-orders-in-the-pd9lr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nImplementation logic\n\n\nthere are some orders\n\nan order can buy ( wit | pgmreddy | NORMAL | 2023-12-09T12:06:50.871952+00:00 | 2023-12-09T12:08:33.235846+00:00 | 28 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nImplementation logic\n\n```\nthere are some orders\n\nan order can buy ( with some buy price say 1$, buy count as 10 )\nan order can sell ( with some sell price say 1$, sell count as 10 )\n\nif order says buy\n if someone is selling <= buy price, then buy it\n buy how many we want\n if some are remaining, put it back to seller\n while doing start from least seller\n buy all you can\n then go to another seller which is selling least\n until we are done with buy all we want to buy\n if we cannot buy all the count we need\n then we add ourselves to buyers in future with price & remaining count\n\nif order says sell\n similar to above\n but reverse\n buy<->sell, least will be max, etc\n\nonce all the order are processed\n how many count of orders are remaining to buy or sell?\n sum them all & return ( this left over is called backlog )\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunction getNumberOfBacklogOrders(orders) {\n const MOD = 1e9 + 7\n const BUY = 0\n const SELL = 1\n const minSellers = new PriorityQueue({ compare: (a, b) => a[0] - b[0] })\n const maxBuyers = new PriorityQueue({ compare: (a, b) => b[0] - a[0] })\n for (const [currentOrderPrice, currentOrders, orderType] of orders) {\n switch (orderType) {\n case BUY:\n {\n let [buyMaxPriceForEachUnit, buyCount] = [currentOrderPrice, currentOrders]\n while (buyCount > 0 && !minSellers.isEmpty()\n && minSellers.front()[0] <= buyMaxPriceForEachUnit) {\n const [sellerPrice, sellerOrderCount] = minSellers.dequeue()\n const buyCountPossible = Math.min(buyCount, sellerOrderCount)\n buyCount -= buyCountPossible\n const sellerOrderCountRemaining = sellerOrderCount - buyCountPossible\n if (sellerOrderCountRemaining > 0) {\n minSellers.enqueue([sellerPrice, sellerOrderCountRemaining])\n }\n }\n if (buyCount > 0) maxBuyers.enqueue([buyMaxPriceForEachUnit, buyCount])\n }\n break\n case SELL:\n {\n let [sellMinPriceForEachUnit, sellCount] = [currentOrderPrice, currentOrders]\n while (sellCount > 0 && !maxBuyers.isEmpty()\n && maxBuyers.front()[0] >= sellMinPriceForEachUnit) {\n const [buyerPrice, buyerOrderCount] = maxBuyers.dequeue()\n const sellCountPossible = Math.min(sellCount, buyerOrderCount)\n sellCount -= sellCountPossible\n const buyerOrderCountRemaining = buyerOrderCount - sellCountPossible\n if (buyerOrderCountRemaining > 0) {\n maxBuyers.enqueue([buyerPrice, buyerOrderCountRemaining])\n }\n }\n if (sellCount > 0) {\n minSellers.enqueue([sellMinPriceForEachUnit, sellCount])\n }\n }\n break\n }\n }\n let backlog = 0\n while (!maxBuyers.isEmpty()) {\n const [buyerPrice, buyerOrderCount] = maxBuyers.dequeue()\n backlog += buyerOrderCount\n backlog %= MOD\n }\n while (!minSellers.isEmpty()) {\n const [sellerPrice, sellerOrderCount] = minSellers.dequeue()\n backlog += sellerOrderCount\n backlog %= MOD\n }\n return backlog\n}\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
number-of-orders-in-the-backlog | Using Sorted dictionary | using-sorted-dictionary-by-abhinandhukr-2dzu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | abhinandhukr | NORMAL | 2023-12-06T18:07:47.124041+00:00 | 2023-12-06T18:07:47.124061+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int GetNumberOfBacklogOrders(int[][] orders) {\n var buyOrders = new SortedDictionary<long, long>(Comparer<long>.Create((x, y) => y.CompareTo(x)));\n\n var sellOrders = new SortedDictionary<long, long>();\n\n foreach(var bid in orders){\n long price = bid[0];\n long amount = bid[1];\n var type = bid[2];\n\n if(type == 0){ // buy order\n while(amount > 0 && sellOrders.Count > 0 && sellOrders.First().Key <= price \n )\n {\n var sell = sellOrders.First();\n\n var sellAmount = Math.Min(amount, sell.Value);\n amount -= sellAmount;\n if(sell.Value == sellAmount){\n //buyOrders.Add(price, amount - sellAmount); \n sellOrders.Remove(sell.Key);\n }else{\n sellOrders[sell.Key] = sellOrders[sell.Key] - sellAmount;\n }\n }\n\n if(amount > 0){\n buyOrders[price] = buyOrders.GetValueOrDefault(price) + amount;\n }\n }else{\n while(amount > 0 && buyOrders.Count > 0 && buyOrders.First().Key >= price)\n {\n var buy = buyOrders.First();\n\n var buyAmount = Math.Min(amount, buy.Value);\n amount -= buyAmount;\n if(buy.Value == buyAmount){\n //sellOrders.Add(price, amount - buyAmount); \n buyOrders.Remove(buy.Key);\n }else{\n buyOrders[buy.Key] = buyOrders[buy.Key] - buyAmount;\n }\n }\n\n if(amount > 0){\n sellOrders[price] = sellOrders.GetValueOrDefault(price) + amount;\n }\n }\n\n }\n return (int)((sellOrders.Values.Sum() + buyOrders.Values.Sum()) % (Math.Pow(10, 9) + 7));\n\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
number-of-orders-in-the-backlog | Easy to understand JavaScript solution (Priority Queue) | easy-to-understand-javascript-solution-p-mt4x | Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n\nvar getNumberOfBacklogOrders = function(orders) {\n const MODULO = 10 ** 9 | tzuyi0817 | NORMAL | 2023-11-10T03:03:42.717437+00:00 | 2023-11-10T03:03:42.717458+00:00 | 24 | false | # Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nvar getNumberOfBacklogOrders = function(orders) {\n const MODULO = 10 ** 9 + 7;\n const buyQueue = new MaxPriorityQueue({ priority:x => x.price });\n const sellQueue = new MinPriorityQueue({ priority:x => x.price });\n const comparePrice = ({ isBuy, price, checkQueue }) => {\n const backlogPrice = checkQueue.front().element.price;\n\n return isBuy ? backlogPrice <= price : backlogPrice >= price;\n };\n let result = 0;\n \n for (let [price, amount, orderType] of orders) {\n const isBuy = orderType === 0;\n const currentQueue = isBuy ? buyQueue : sellQueue;\n const checkQueue = isBuy ? sellQueue : buyQueue;\n \n while (!checkQueue.isEmpty() && amount > 0 && comparePrice({ isBuy, price, checkQueue })) {\n const order = checkQueue.dequeue().element;\n\n if (amount >= order.amount) {\n amount -= order.amount;\n } else {\n order.amount -= amount;\n amount = 0;\n checkQueue.enqueue(order);\n }\n }\n if (amount === 0) continue;\n currentQueue.enqueue({ price, amount });\n }\n\n while (!buyQueue.isEmpty()) result += buyQueue.dequeue().element.amount;\n while (!sellQueue.isEmpty()) result += sellQueue.dequeue().element.amount;\n return result % MODULO;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
number-of-orders-in-the-backlog | [Python3] OOD | Interview Friendly Solution | python3-ood-interview-friendly-solution-wb6w1 | Complexity\nTime: O(nlogn)\nSpace: O(n)\n\n\n# Code\n\nimport abc\nimport heapq\nfrom enum import Enum\nfrom abc import ABC, abstractmethod\nfrom typing import | specbug | NORMAL | 2023-11-08T08:29:38.733937+00:00 | 2023-11-08T08:30:20.565280+00:00 | 20 | false | # Complexity\nTime: $$O(nlogn)$$\nSpace: $$O(n)$$\n\n\n# Code\n```\nimport abc\nimport heapq\nfrom enum import Enum\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, List\n\nMOD = int(1e9+7)\nclass OrderType(Enum):\n BUY = 0\n SELL = 1\n\n @classmethod\n def get(cls, order_type_id: int):\n order_type_map = {k.value: k for k in cls}\n return order_type_map[order_type_id]\n\nclass Backlog(ABC):\n def __init__(self):\n self.__heap = []\n self.__price_amount_map = dict()\n self.__total_amount = 0\n\n def get_total_amount(self) -> int:\n return self.__total_amount%MOD\n\n def add_to_total_amount(self, amount: int):\n self.__total_amount += amount\n\n def remove_from_total_amount(self, amount: int):\n self.__total_amount -= amount\n\n def peek(self) -> Optional[int]:\n if len(self.__heap) == 0:\n return None\n return self.__heap[0]\n\n def push(self, price: int):\n heapq.heappush(self.__heap, price)\n\n def pop(self) -> Optional[int]:\n if self.peek() is None:\n return\n return heapq.heappop(self.__heap)\n\n def get_orders_for_price(self, price: int) -> int:\n return self.__price_amount_map.get(price, 0)\n\n def update_orders_for_price(self, price: int, amount: int):\n self.__price_amount_map[price] = amount\n\n @abstractmethod\n def add(self, price: int, amount: int): ...\n\n @abstractmethod\n def remove(self, amount: int): ...\n\nclass BuyBacklog(Backlog):\n def peek(self) -> Optional[int]:\n top = super().peek()\n if top is None:\n return\n return -top\n\n def push(self, price: int):\n price *= -1\n super().push(price=price)\n\n def pop(self) -> Optional[int]:\n val = super().pop()\n if val is None:\n return\n return -val\n\n def add(self, price: int, amount: int):\n existing_orders_for_price = self.get_orders_for_price(price=price)\n if existing_orders_for_price == 0:\n self.push(price=price)\n new_orders_for_price = existing_orders_for_price + amount\n self.add_to_total_amount(amount=amount)\n self.update_orders_for_price(price=price, amount=new_orders_for_price)\n\n def remove(self, amount: int) -> Optional[int]:\n max_buy_price = self.peek()\n if max_buy_price is None:\n return\n max_price_amount = self.get_orders_for_price(price=max_buy_price)\n amount = min(amount, max_price_amount)\n self.remove_from_total_amount(amount=amount)\n max_price_amount -= amount\n\n self.update_orders_for_price(price=max_buy_price, amount=max_price_amount)\n if max_price_amount == 0:\n self.pop()\n return max_buy_price\n\nclass SellBacklog(Backlog):\n def add(self, price: int, amount: int):\n existing_orders_for_price = self.get_orders_for_price(price=price)\n if existing_orders_for_price == 0:\n self.push(price=price)\n new_orders_for_price = existing_orders_for_price + amount\n self.add_to_total_amount(amount=amount)\n self.update_orders_for_price(price=price, amount=new_orders_for_price)\n\n def remove(self, amount: int) -> Optional[int]:\n min_buy_price = self.peek()\n if min_buy_price is None:\n return\n min_price_amount = self.get_orders_for_price(price=min_buy_price)\n amount = min(amount, min_price_amount)\n self.remove_from_total_amount(amount=amount)\n min_price_amount -= amount\n self.update_orders_for_price(price=min_buy_price, amount=min_price_amount)\n if min_price_amount == 0:\n self.pop()\n return min_buy_price\n\n\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n buy_backlog = BuyBacklog()\n sell_backlog = SellBacklog()\n\n for price, amount, order_type_id in orders:\n order_type = OrderType.get(order_type_id=order_type_id)\n if order_type == OrderType.BUY:\n min_sell_price = sell_backlog.peek()\n while amount > 0 and min_sell_price is not None and min_sell_price <= price:\n sell_amount = sell_backlog.get_orders_for_price(price=min_sell_price)\n sell_backlog.remove(amount=amount)\n amount -= sell_amount\n min_sell_price = sell_backlog.peek()\n if amount > 0:\n buy_backlog.add(price=price, amount=amount)\n elif order_type == OrderType.SELL:\n max_buy_price = buy_backlog.peek()\n while amount > 0 and max_buy_price is not None and max_buy_price >= price:\n buy_amount = buy_backlog.get_orders_for_price(price=max_buy_price)\n buy_backlog.remove(amount=amount)\n amount -= buy_amount\n max_buy_price = buy_backlog.peek()\n if amount > 0:\n sell_backlog.add(price=price, amount=amount)\n else:\n raise KeyError(f\'invalid order type\')\n\n total_remaining_amount = (sell_backlog.get_total_amount() + buy_backlog.get_total_amount())%MOD\n return total_remaining_amount\n\n``` | 0 | 0 | ['Python3'] | 0 |
find-the-array-concatenation-value | Pow and Log | pow-and-log-by-votrubac-8uij | We use pow and log10 to avoid string conversion.\n\n## One-Liner\nOne-liner for my functional frieds. For those who are yet to embrace this, see the raw loops v | votrubac | NORMAL | 2023-02-12T04:32:45.966488+00:00 | 2023-02-12T21:43:57.714525+00:00 | 2,404 | false | We use `pow` and `log10` to avoid string conversion.\n\n## One-Liner\nOne-liner for my functional frieds. For those who are yet to embrace this, see the raw loops version below. \n\n**C++**\n```cpp\nlong long findTheArrayConcVal(vector<int>& n) {\n return transform_reduce(begin(n), begin(n) + n.size() / 2, rbegin(n), 0LL, plus{}, [](int l, int r){\n return l * pow(10, (int)log10(r) + 1);}) \n + accumulate(begin(n) + n.size() / 2, end(n), 0LL);\n} \n```\n\n## Raw Loops\n**C++**\n```cpp\nlong long findTheArrayConcVal(vector<int>& nums) {\n long long res = 0, sz = nums.size();\n for (int i = 0, j = sz - 1; i <= j; ++i, --j)\n if (i < j)\n res += nums[i] * pow(10, (int)log10(nums[j]) + 1) + nums[j];\n else\n res += nums[i];\n return res;\n}\n``` | 46 | 1 | ['C'] | 7 |
find-the-array-concatenation-value | ✅Python3 || C++✅ Beats 100% | python3-c-beats-100-by-abdullayev_akbar-z6ni | \n\n# Please UPVOTE \uD83D\uDE0A\n\n## Python3\n\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n ans=0\n if len(num | abdullayev_akbar | NORMAL | 2023-02-12T04:40:54.328534+00:00 | 2023-03-26T10:15:15.673636+00:00 | 1,829 | false | \n\n# Please UPVOTE \uD83D\uDE0A\n\n## Python3\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n ans=0\n if len(nums)%2==1:\n ans=nums[len(nums)//2]\n for i in range(len(nums)//2):\n ans+=int(str(nums[i])+str(nums[len(nums)-1-i]))\n return ans\n \n```\n## C++\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long int n=nums.size(),ans=0;\n if(n%2){\n ans=nums[n/2];\n }\n for(int i=0;i<n/2;i++){\n int y=nums[n-1-i],x=nums[i];\n while(y){\n x*=10;\n y/=10;\n }\n x+=nums[n-i-1];\n ans+=x;\n }\n return ans;\n\n }\n};\n```\n\n | 27 | 1 | ['Python3'] | 5 |
find-the-array-concatenation-value | ✅🚀 c++ very easy two pointer approach✅🚀 | c-very-easy-two-pointer-approach-by-sura-ngs6 | \n# Code\n\nclass Solution {\npublic:\n/* simple two pointer approach --> T.C : O(N)\n\nalgo:\n\n1. Take first and last element from array.\n2. convert them int | suraj_jha989 | NORMAL | 2023-02-12T04:03:26.447017+00:00 | 2023-02-12T04:54:09.352981+00:00 | 1,386 | false | \n# Code\n```\nclass Solution {\npublic:\n/* simple two pointer approach --> T.C : O(N)\n\nalgo:\n\n1. Take first and last element from array.\n2. convert them into string and concatenate them.\n3. add result to answer\n4. do this until all elements are traversed.\n*/\n long long findTheArrayConcVal(vector<int>& nums) {\n long long n=nums.size();\n long long ans=0;\n \n if(n==1) return nums[0];\n \n long long i=0,j=n-1;\n while(i<j){\n string s=to_string(nums[i]) + to_string(nums[j]);\n //cout<<s<<endl;\n ans += stoi(s);\n i++;\n j--;\n }\n \n if(i==j) ans += nums[i];\n return ans;\n \n }\n};\n```\n# Please do upvote if you find this helpful\u2764\uFE0F! :) | 17 | 0 | ['C++'] | 3 |
find-the-array-concatenation-value | 🔥🔥 Simple C++ || to_string() function | simple-c-to_string-function-by-atharva_k-tssn | \nclass Solution {\npublic:\n #define ll long long\n long long findTheArrayConcVal(vector<int>& nums) \n {\n ll res = 0;\n int low = 0;\n | atharva_kulkarni1 | NORMAL | 2023-02-12T04:17:25.323215+00:00 | 2023-02-12T04:21:17.189917+00:00 | 993 | false | ```\nclass Solution {\npublic:\n #define ll long long\n long long findTheArrayConcVal(vector<int>& nums) \n {\n ll res = 0;\n int low = 0;\n int high = nums.size()-1;\n \n while(low < high)\n {\n string temp = to_string(nums[low]) + to_string(nums[high]);\n \n // cout << temp;\n \n res += stoi(temp);\n \n low++;\n high--;\n }\n \n if(low == high)\n {\n string temp = to_string(nums[low]);\n \n res += stoi(temp);\n }\n \n return res;\n \n }\n};\n``` | 13 | 1 | ['String', 'C', 'C++'] | 0 |
find-the-array-concatenation-value | Simple java solution | simple-java-solution-by-siddhant_1602-wcoo | \n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n | Siddhant_1602 | NORMAL | 2023-02-12T04:00:52.573681+00:00 | 2023-02-12T04:03:18.243242+00:00 | 2,091 | false | \n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long m=0;\n if(nums.length==1)\n {\n return (long)(nums[0]);\n }\n for(int i=0,j=nums.length-1;i<j;i++,j--)\n {\n String p=String.valueOf(nums[i])+String.valueOf(nums[j]);\n long q=Long.parseLong(p);\n m+=q;\n }\n if(nums.length%2==1)\n {\n return m+(long)(nums[nums.length/2]);\n }\n return m;\n }\n}\n``` | 12 | 0 | ['Java'] | 3 |
find-the-array-concatenation-value | Python 3 || 5 lines, iteration || T/S: 86% / 72% | python-3-5-lines-iteration-ts-86-72-by-s-3jkk | \nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n\n n=len(nums)\n\n ans=nums[n//2] if n%2 else 0\n\n for i in | Spaulding_ | NORMAL | 2023-02-12T08:12:24.464758+00:00 | 2024-06-21T16:50:53.695488+00:00 | 795 | false | ```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n\n n=len(nums)\n\n ans=nums[n//2] if n%2 else 0\n\n for i in range(n//2): \n ans += int(str(nums[i])+str(nums[-i-1]))\n \n return ans\n```\n[https://leetcode.com/problems/find-the-array-concatenation-value/submissions/1295835207/](https://leetcode.com/problems/find-the-array-concatenation-value/submissions/1295835207/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(nums)`.\n | 9 | 0 | ['Python3'] | 0 |
find-the-array-concatenation-value | Concatenate String ✅ || Easy Understanding ✅ | concatenate-string-easy-understanding-by-qu80 | Hi,\n\nWe have to iterate through the loop and add to result.\n\nKindly upvote if its helpful.\n```\n public long findTheArrayConcVal(int[] nums) {\n | Surendaar | NORMAL | 2023-02-12T04:04:02.986284+00:00 | 2023-02-12T07:05:57.581535+00:00 | 667 | false | Hi,\n\nWe have to iterate through the loop and add to result.\n\nKindly upvote if its helpful.\n```\n public long findTheArrayConcVal(int[] nums) {\n long res=0;\n for(int i=0; i<(nums.length/2); i++){\n \tString tmp = nums[i]+""+nums[nums.length-1-i];\n \tres = res + Integer.parseInt(tmp);\n }\n if(nums.length%2==1){\n \tres = res + nums[(nums.length/2)];\n }\n return res;\n }\n\t | 9 | 0 | ['String', 'Java'] | 1 |
find-the-array-concatenation-value | Python | 100% Faster | Easy Solution✅ | python-100-faster-easy-solution-by-gmana-6yxf | Code\u2705\n\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n concatenation = 0\n while len(nums)>0:\n if | gmanayath | NORMAL | 2023-02-12T15:54:51.305845+00:00 | 2023-02-12T15:58:40.813907+00:00 | 1,219 | false | # Code\u2705\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n concatenation = 0\n while len(nums)>0:\n if len(nums)>1:\n concatenation += int(str(nums[0])+str(nums[-1]))\n del nums[-1]\n else:\n concatenation += nums[0]\n del nums[0]\n return concatenation\n```\n\n | 8 | 0 | ['Python', 'Python3'] | 0 |
find-the-array-concatenation-value | ✅ very fast C++ | with explanation | very-fast-c-with-explanation-by-coding_m-dxsv | Thought process\n\nFirst: We need to concantenate every integer with it\'s corresponding integer at the same position it is from the other end.\nFor eg, in [23, | coding_menance | NORMAL | 2023-02-12T07:18:40.890262+00:00 | 2023-02-12T17:51:11.832407+00:00 | 506 | false | # Thought process\n\n**First:** We need to concantenate every integer with it\'s corresponding integer at the same position it is from the other end.\nFor eg, in **[23, 54, 65, 24, 87]** we need to concantanate *23 & 87* to get **2387** and then *54 & 24* to get **5424**. Since this list contains odd number of elements there is a middle element **65** which can\'t pair up with any other element; so keep it as *65* only.\n\n**Second:** Now we need to add all the concantanated elements to a common variable. In our case it is **total**. In case of odd number of elements we separately add the middle element (in our case, 65) to total.\n\n*Note that we are performing the above to steps simultaneously. So what does it mean? We form a concatenated pair we add it to **total** variable before proceding with the next pair. It would get much clearer in the code*\n\nSo you might be wondering how do we concatenate the two integers in a pair? Let\'s see:\n\nIn **[23, 54, 65, 24, 87]** we need to first concatenate 23 and 87, right? To put 23 before 87 ( to get 2387) we need to add 2300 to 87 [that\'s one way of doing it]; we multiply 23 by 10 as many times required *to reduced 87 to 0 by dividing it with 10*.\n\nWe enter a loop with i iterating from 0 to n/2.\nFor i=0;\nnums[n/2-1-i]/=10 which is dividing 87 by 10 to give 8[int/int is int not decimal]; we multiply 23 by 10\nthen again, nums[n/2-1-i]/=10 which is dividing 8 by 10 to give 0[int/int is int not decimal]; we multiply 230 by 10\n\nthen we add 2300 and 87 to **total** variable and continue doing the same for other variables\n\nDon\'t Worry if you are still confused, have a look at the code, you will get it :)\n\n# Code\n\n``` C++ []\nclass Solution {\npublic:\n long findTheArrayConcVal(vector<int>& nums) {\n int n = nums.size(), x{0};\n long total{0};\n\n // we iterate through the i=0 to i=n/2\n for (int i{0}; i<n/2; i++) {\n\n // we store the (n-i-1)th term in variable x, as we are going to tamper with it\n x = nums[n-i-1];\n // we see the number of places present before the decimal in the (n-i-1)th term and\n // multiply the i th term by 10 so that we get the correct number to add to total variable\n // we repeat this process till the (n-i-1)th term is 0\n while (nums[n-i-1]>0) {\n nums[n-i-1]/=10;\n nums[i]*=10;\n }\n total+=x+nums[i];\n }\n\n // if there are a odd number of term the middle term is unaccounted for\n // as it is not include in the iteration of i from 0 to n/2\n if (n%2==1) total+=nums[n/2];\n return total;\n }\n};\n```\n\n\n | 8 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Very Simple & Easy to Understand Solution | very-simple-easy-to-understand-solution-2ckkl | \n# Code\n\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long ans = 0;\n int n = nums.size();\n | kreakEmp | NORMAL | 2023-02-12T04:15:09.045044+00:00 | 2023-02-12T04:15:09.045085+00:00 | 2,381 | false | \n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long ans = 0;\n int n = nums.size();\n for(int i = 0; i < n/2; ++i){\n string t = to_string(nums[i]) + to_string(nums[n - i - 1]);\n ans += stol(t);\n }\n if(n % 2) ans += nums[n/2];\n return ans;\n }\n};\n```\n\nHere is an article of my recent interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted | 8 | 0 | ['C++'] | 2 |
find-the-array-concatenation-value | PYTHON || Very Simple and Easy to Understand Code in Python 🌟✅ | python-very-simple-and-easy-to-understan-z0jk | \n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n O(n) \n\n# Code\n\nclass Solution:\n def findTheArrayConcVal(self, nums: | DeepakNishad | NORMAL | 2023-02-12T04:35:48.451381+00:00 | 2023-02-12T04:36:00.983575+00:00 | 626 | false | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n) \n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n i=0\n j=len(nums)-1\n res=0\n while i<=j:\n if i==j: \n res+=int(nums[i])\n elif i!=j:\n res+=int(str(nums[i])+str(nums[j]))\n i+=1\n j-=1\n return res\n``` | 7 | 0 | ['Two Pointers', 'Python3'] | 3 |
find-the-array-concatenation-value | C++ | Easy Solution | c-easy-solution-by-iam_invincible-9cwc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | iam_invincible | NORMAL | 2023-02-12T04:08:53.831657+00:00 | 2023-02-12T04:08:53.831698+00:00 | 193 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#include<bits/stdc++.h>\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n \n long long int n=nums.size();\n long long int i=0,j=n-1;\n long long int ans=0;\n while(i<j)\n {\n string s1 = to_string(nums[i]);\n string s2 = to_string(nums[j]);\n string s = s1 + s2;\n long long int c = stoi(s);\n ans+=c;\n i++;\n j--;\n }\n if(n%2)\n ans+=nums[n/2];\n return ans; \n }\n};\n``` | 6 | 0 | ['Two Pointers', 'C++'] | 1 |
find-the-array-concatenation-value | Java || Two Pointers || CF | java-two-pointers-cf-by-mmohmedjasim2005-ayxl | ApproachWe use a two-pointer technique (with pointers l and r) to compute the concatenation value of an array efficientlyInitialization:The left pointer (l) is | mmohmedjasim2005 | NORMAL | 2025-01-23T15:23:04.630844+00:00 | 2025-01-23T15:23:04.630844+00:00 | 223 | false | # Approach
**We use a two-pointer technique (with pointers l and r) to compute the concatenation value of an array efficiently**
## Initialization:
The left pointer (l) is initialized to the start of the array (0), and the right pointer (r) is initialized to the end of the array (nums.length - 1)
A variable con is initialized to 0 to store the cumulative concatenation value
## Two-Pointer Traversal:
The pointers l and r move toward each other while processing elements at both ends of the array
- If the two pointers meet (l == r), it means there is a single middle element remaining in the array.
1. Add the value directly to con
2. Break out of the loop, as all elements have been processed
- If the two pointers do not meet:
1. Convert the values at nums[l] and nums[r] into strings
2. Concatenate the two string values (nums[l] + nums[r])
3. Convert the concatenated string back to an integer and add it to con
After processing a pair of elements, increment the left pointer (l++) and decrement the right pointer (r--)
# Code
```java []
class Solution {
public long findTheArrayConcVal(int[] nums) {
int l = 0;
int r = nums.length - 1;
long con = 0;
String temp="";
while (l <= r) {
if (l == r) {
temp=String.valueOf(nums[l]);
}
else{
temp = String.valueOf(nums[l]) + String.valueOf(nums[r]);
}
con += Integer.parseInt(temp);
l++;
r--;
}
return con;
}
}
``` | 5 | 0 | ['Java'] | 1 |
find-the-array-concatenation-value | Java || 2 Solution❤️❤️ || StringBuilder || 2 Pointer || Easy Solution|| | java-2-solution-stringbuilder-2-pointer-4440h | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | saurabh_kumar1 | NORMAL | 2023-08-29T20:05:49.700965+00:00 | 2023-08-29T20:05:49.700983+00:00 | 319 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n int low = 0 , high = nums.length-1; long ans = 0L;\n StringBuilder temp = new StringBuilder();\n while(low<=high){\n if(low!=high) temp.append(nums[low]).append(nums[high]);\n else temp.append(nums[low]);\n low++; high--;\n ans+=(Integer.parseInt(temp.toString()));\n temp.setLength(0);\n }\n return ans;\n\n // ANOTHER SOLUTION(try this one)\n\n // long ans = 0L;\n // int low = 0 , high = nums.length-1;\n // while(low <= high){\n // String str1 = Long.toString(nums[low]) , str2 = Long.toString(nums[high]);\n // str1 = str1 + str2;\n // if(low == high) ans += nums[low]; \n // else ans +=(Long.parseLong(str1));\n // low++; high--;\n // }\n // return ans;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | C++ | Easy Approach | 4 Lines of Code | c-easy-approach-4-lines-of-code-by-_hori-hh0z | \n# Approach\n Describe your approach to solving the problem. \nUsing to_string and stoi\n\n\n# Code\n\nclass Solution {\npublic:\n long long findTheArrayCon | _horiZon_OP | NORMAL | 2023-02-12T04:56:17.889123+00:00 | 2023-02-12T04:57:05.797890+00:00 | 246 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing `to_string` and `stoi`\n\n\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long n = size(nums), i = 0, j = n-1,ans = 0;\n while(i<j) ans += stoi((to_string(nums[i++])+to_string(nums[j--])));\n if(i==j) ans+=(int)(nums[i]);\n return ans; \n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | BEGINNER FRIENDLY PYTHON PROGRAM [ BEATS 88% OF USERS ] | beginner-friendly-python-program-beats-8-gdzz | Intuition\nUsing for loop and string slicing\n\n# Approach\n Describe your approach to solving the problem. \nwe use for loop to iterate over the list and take | chorko_c | NORMAL | 2023-10-31T05:33:38.124878+00:00 | 2023-10-31T05:33:38.124908+00:00 | 102 | false | # Intuition\nUsing for loop and string slicing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe use for loop to iterate over the list and take the 1st and last elements as string and concatenate\n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n ls=[]\n x=-1\n l=len(nums)//2\n \n \n for i in range(l):\n \n ls.append(int(str(nums[i])+str(nums[x])))\n x-=1\n \n if len(nums)%2==0:\n return sum(ls)\n else:\n return sum(ls)+nums[l]\n``` | 4 | 0 | ['Python3'] | 0 |
find-the-array-concatenation-value | C++ || EASY TO UNDERSTAND | c-easy-to-understand-by-ganeshkumawat874-jjyq | Code\n\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int i = 0,j=nums.size()-1,x,y;\n long long int ans=0;\ | ganeshkumawat8740 | NORMAL | 2023-05-15T12:12:34.580862+00:00 | 2023-05-15T12:12:34.580910+00:00 | 744 | false | # Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int i = 0,j=nums.size()-1,x,y;\n long long int ans=0;\n while(i<j){\n x = nums[j];\n y = 0;\n while(x){\n y++;\n x /= 10;\n }\n ans += (nums[i]*1LL*pow(10,y)+nums[j]);\n i++;\n j--;\n }\n if(i==j){\n ans += nums[i];\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++'] | 0 |
find-the-array-concatenation-value | Easy to understand Sol for beginners | easy-to-understand-sol-for-beginners-by-jf3ay | Intuition\n Describe your first thoughts on how to solve this problem. \n1. to_string function to convert the integer to string for concatenation.\n2. stoi() to | Adit_14 | NORMAL | 2023-03-17T16:20:01.966818+00:00 | 2023-03-17T16:20:01.966862+00:00 | 897 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. to_string function to convert the integer to string for concatenation.\n2. stoi() to convert string back into integer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterating over the first half of the nums vector and concatenating the values at each index(i) with the corresponding value at the opposite end of the vector(n-1-i). This concatenated value is then converted to an integer and added to sum.\n2. If n is odd, the value of nums[n/2] is added to sum.\n3. Finally, sum is returned as the result of the function\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long sum=0;\n int n=nums.size();\n for(int i=0;i<n/2;i++)\n {\n string res= to_string(nums[i]) + to_string(nums[n-1-i]);\n sum+=stoi(res);\n }\n if(n%2!=0)\n {\n sum+=nums[n/2];\n }\n return sum;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Java | 8 lines | Simple and clean code | Beats 100% | java-8-lines-simple-and-clean-code-beats-ycti | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | judgementdey | NORMAL | 2023-02-12T16:52:36.150245+00:00 | 2023-02-13T00:47:10.954563+00:00 | 134 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n var n = nums.length;\n var ans = 0L;\n \n for (int i = 0, j = n-1; i < j; i++, j--) {\n for (var r = nums[j]; r > 0; r /= 10, nums[i] *= 10);\n ans += nums[i] + nums[j];\n }\n if (n % 2 == 1)\n ans += nums[n/2];\n \n return ans;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
find-the-array-concatenation-value | JavaScript short and sweet | javascript-short-and-sweet-by-ramrad-adhy | js\nconst findTheArrayConcVal = nums => {\n let output = 0;\n let i = 0;\n let j = nums.length - 1;\n\n while (i <= j) {\n output += Number(i === j ? num | ramrad | NORMAL | 2023-02-12T14:56:28.490664+00:00 | 2023-02-12T14:56:28.490694+00:00 | 371 | false | ```js\nconst findTheArrayConcVal = nums => {\n let output = 0;\n let i = 0;\n let j = nums.length - 1;\n\n while (i <= j) {\n output += Number(i === j ? nums[i] : `${nums[i]}` + `${nums[j]}`);\n i++;\n j--;\n }\n return output;\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
find-the-array-concatenation-value | Using lambda function,to_string and stoll | using-lambda-functionto_string-and-stoll-ickw | Complexity\n- Time complexity:\nO(n/2)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n typedef long long ll;\n long long findTheArra | harsh_patell21 | NORMAL | 2023-02-12T08:26:58.253377+00:00 | 2023-02-12T08:26:58.253410+00:00 | 40 | false | # Complexity\n- Time complexity:\n$$O(n/2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n typedef long long ll;\n long long findTheArrayConcVal(vector<int>& nums) {\n ll n=nums.size();\n ll total=0;\n for(int i=0;i<n/2;i++){\n [&total](int a,int b){total+=stoll(to_string(a)+to_string(b));}(nums[i],nums[n-i-1]);\n }\n if(n%2!=0){\n total+=nums[n/2];\n }\n return total;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | ✅C# || ✅JAVA || 🐍Python || Easy to Understand || ⏳Beats 100% | c-java-python-easy-to-understand-beats-1-zt3c | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | santhosh1608 | NORMAL | 2023-02-12T06:05:06.548134+00:00 | 2023-02-12T06:05:06.548187+00:00 | 529 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Upvote Please \uD83D\uDE09\uD83D\uDE09\uD83D\uDE4C\n# Code\n```\npublic class Solution {\n public long FindTheArrayConcVal(int[] nums) {\n int start=0;\n int end=nums.Length-1;\n long result=0;\n while (start <= end){\n if(start == end){\n result+=nums[start];\n start+=1;\n }\n else{\n int checkEnd=1;\n while(checkEnd <= nums[end]){\n checkEnd*=10;\n }\n result+=(long)nums[start]*checkEnd+nums[end];\n start+=1;\n end-=1;\n }\n }\n return result;\n }\n}\n``` | 4 | 0 | ['C#'] | 0 |
find-the-array-concatenation-value | EASY TO UNDERSTAND C++ || POW AND LOG || TWO POINTERS | easy-to-understand-c-pow-and-log-two-poi-vxax | \nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long int ans=0,x,b;\n int i = 0, j = nums.size()-1;\n | yash___sharma_ | NORMAL | 2023-02-12T05:48:32.875367+00:00 | 2023-02-12T05:48:32.875410+00:00 | 175 | false | ```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long int ans=0,x,b;\n int i = 0, j = nums.size()-1;\n while(i<j){\n x = nums[j], b = 0;\n while(x){\n b++;\n x /= 10;\n }\n ans = ans + nums[i]*1LL*pow(10,b)+nums[j];\n i++;\n j--;\n }\n if(i==j){\n ans += nums[i];\n }return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Two Pointers', 'C', 'C++'] | 0 |
find-the-array-concatenation-value | Two pointer easy | two-pointer-easy-by-feistyfawn-tgvr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | feistyfawn | NORMAL | 2023-02-12T05:19:01.971335+00:00 | 2023-02-12T13:47:24.731952+00:00 | 416 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int [] nums) {\n int P1=0,P2=nums.length-1;\n String s="";\n long sum=0;\n while(P1<=P2){\n if(P1==P2)s=String.valueOf(nums[P1]);\n else s=String.valueOf(nums[P1])+String.valueOf(nums[P2]);\n sum+=Integer.parseInt(s);\n P1++;\n P2--;\n }\n return sum;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | ✅C++ || EASY && CLEAN && StraightForward CODE | c-easy-clean-straightforward-code-by-abh-y8b3 | \n\nT->O(n/2) && S->O(1)\n\n\tclass Solution {\n\tpublic:\n\t\tlong long findTheArrayConcVal(vector& nums) {\n\t\t\tint n = nums.size();\n\t\t\tint i = 0,j = n- | abhinav_0107 | NORMAL | 2023-02-12T04:22:21.882012+00:00 | 2023-02-12T04:22:40.579618+00:00 | 746 | false | \n\n**T->O(n/2) && S->O(1)**\n\n\tclass Solution {\n\tpublic:\n\t\tlong long findTheArrayConcVal(vector<int>& nums) {\n\t\t\tint n = nums.size();\n\t\t\tint i = 0,j = n-1;\n\t\t\tlong long ans = 0;\n\n\t\t\twhile(j > i){\n\t\t\t\tstring temp = to_string(nums[i]) + to_string(nums[j]);\n\t\t\t\ti++;\n\t\t\t\tj--;\n\t\t\t\tans += stoll(temp);\n\t\t\t}\n\n\t\t\tif(n % 2 == 1) ans += nums[i];\n\n\t\t\treturn ans;\n\t\t}\n\t}; | 4 | 0 | ['Two Pointers', 'C', 'C++'] | 0 |
find-the-array-concatenation-value | Two pointers Python 3 solution | two-pointers-python-3-solution-by-artyom-vf8d | \n\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n result = 0\n\n p1 = 0\n p2 = len(nums) - 1\n\n whi | artyom02 | NORMAL | 2023-06-06T21:19:27.147666+00:00 | 2023-06-06T21:19:27.147724+00:00 | 58 | false | \n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n result = 0\n\n p1 = 0\n p2 = len(nums) - 1\n\n while p1 <= p2:\n if p1 == p2:\n result += int(nums[p1])\n\n else:\n result += int(str(nums[p1]) + str(nums[p2]))\n\n p1 += 1\n p2 -= 1\n\n return result\n``` | 3 | 0 | ['Two Pointers', 'Python3'] | 1 |
find-the-array-concatenation-value | Easy Python Solution using 2 pointers | easy-python-solution-using-2-pointers-by-gbh1 | \n\n# Code\n\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n left=0\n right=len(nums)-1\n total=0\n w | vistrit | NORMAL | 2023-02-17T20:10:50.412642+00:00 | 2023-02-17T20:10:50.412675+00:00 | 490 | false | \n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n left=0\n right=len(nums)-1\n total=0\n while left<=right:\n if left<right:\n total+=int(str(nums[left])+str(nums[right]))\n else:\n total+=nums[left]\n left+=1\n right-=1\n return total\n``` | 3 | 0 | ['Python3'] | 0 |
find-the-array-concatenation-value | C++ easy to understand solution | c-easy-to-understand-solution-by-sahilla-tlwd | Intuition :\nMoving towards middle from extreme ends.\n Describe your first thoughts on how to solve this problem. \n\n# Approach :\nTaking pointer to start and | sahillather002 | NORMAL | 2023-02-16T16:25:53.226425+00:00 | 2023-02-16T16:25:53.226465+00:00 | 1,233 | false | # Intuition :\nMoving towards middle from extreme ends.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\nTaking pointer to start and end , traversing towards each other at constant rate. Applying formula at each iteration to get final result.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code :\nHere is the code:\n```\nclass Solution {\npublic:\n int siz(int n){\n int s = 0;\n while(n>0){\n s++;\n n /= 10;\n }\n return s;\n }\n long long findTheArrayConcVal(vector<int>& nums) {\n if(nums.size()==1)\n return nums[0];\n long long ans = 0;\n int i=0;\n int j = nums.size()-1;\n while(i<j){\n ans += nums[i]*pow(10 , siz(nums[j])) + nums[j];\n i++;\n j--;\n if(i==j)\n ans += nums[j];\n }\n return ans;\n }\n};\n``` | 3 | 0 | ['Array', 'Two Pointers', 'C++'] | 0 |
find-the-array-concatenation-value | ✅C++ beats 100% of submissions ✅ | c-beats-100-of-submissions-by-akshay_ar_-6azk | Intuition\n Describe your first thoughts on how to solve this problem. \n- Just by looking at the word "concatenation", I had got the string approach in my mind | akshay_AR_2002 | NORMAL | 2023-02-12T17:01:11.759622+00:00 | 2023-02-12T17:01:11.759654+00:00 | 265 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Just by looking at the word "concatenation", I had got the string approach in my mind along with its predefined functions.. stoi(used for the conversion of string to integer) and to_string(converts integer value to string).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Iterating over the first half of the nums vector and concatenating the values at each index with the corresponding value at the opposite end of the vector (i.e. if the index is i, the concatenated value is the string representation of nums[i] concatenated with the string representation of nums[n-i-1]). This concatenated value is then converted to an integer and added to a running sum.\n- If n is odd, the value of nums[n/2] is added to sum.\n- Finally, sum is returned as the result of the function.\n\n# Complexity\nTime complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- The time complexity of this function is O(n), where n is the number of elements in the nums vector. This is because the function performs a single loop over the first half of the vector, and each iteration of the loop takes constant time.\n\nSpace complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- The space complexity of this function is O(1), as the function uses a constant amount of memory regardless of the size of the input. The only variables used in the function are an integer n to store the size of the input vector, two long long variables sum and n1 to store intermediate results, and one string variable res to store the concatenated value before converting it to an integer. All of these variables use a constant amount of memory, so the overall space complexity is constant.\n\n# Code\n```\nclass Solution {\npublic:\n typedef long long ll;\n long long findTheArrayConcVal(vector<int>& nums) \n {\n int n = nums.size();\n ll sum = 0;\n ll n1;\n ll n2;\n for (int i = 0; i < n / 2; i++) \n {\n n1 = nums[i];\n n2 = nums[n - i - 1];\n string res = to_string(n1) + to_string(n2);\n sum += stoi(res);\n }\n \n if (n % 2)\n sum += nums[n / 2];\n \n return sum;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Easy Solution | Faster using Two Pointers and Strings 3ms | easy-solution-faster-using-two-pointers-drzj3 | Intuition\n1. We need first element & last element from array -> so we will use Two Pointer to solve.\n2. We need to Concate these two elements from array -> so | harshadnavsar | NORMAL | 2023-02-12T07:33:46.486528+00:00 | 2023-02-12T07:33:46.486555+00:00 | 249 | false | # Intuition\n1. We need first element & last element from array -> so we will use Two Pointer to solve.\n2. We need to Concate these two elements from array -> so we will use Strings.\n3. And then we need to process the ans. \n\n# Approach\nWe will get both elements from pointers (low,high) and then convert them into Strings , and then concate them, store the result into another string.\nNow we have to add the resultant string in the form of Integer so, convert the resultant string into Integer.\n\nNow we have to cases:\n \n\n\nCase 2:\nIf we run a loop (low <= high) then our middle element will get concatenated twice, & if not then our middle element will be remained from getting concatenated.\n\nTo avoid this if array length is odd then after loop directly add the middle element. \n\n# Complexity\n- Time complexity: O(n)\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n \n int low = 0;\n int high = nums.length-1;\n \n long ans = 0;\n \n while(low < high){\n \n String s1 = Integer.toString(nums[low]);\n String s2 = Integer.toString(nums[high]);\n \n String s3 = s1 + s2;\n \n ans += (Integer.parseInt(s3));\n \n low++;\n high--;\n }\n \n if(nums.length%2 != 0)\n ans += nums[low];\n \n return ans;\n }\n}\n``` | 3 | 0 | ['Two Pointers', 'String', 'Java'] | 0 |
find-the-array-concatenation-value | Find the Array Concatenation Value || Python || Easy Solution || 2 Approaches || Beats 100 % | find-the-array-concatenation-value-pytho-24k4 | Step-by-Step Explanation - Code 11. Initialize variables
n = len(nums) gets the length of the input array nums.
concatenation_value = 0 initializes a variable t | aishvgandhi | NORMAL | 2025-01-26T09:56:52.105555+00:00 | 2025-01-26T09:56:52.105555+00:00 | 53 | false | # **Step-by-Step Explanation - Code 1**
## 1. **Initialize variables**
- `n = len(nums)` gets the length of the input array `nums`.
- `concatenation_value = 0` initializes a variable to accumulate the result.
## 2. **Loop through half of the array**
```python
for i in range(n // 2):
```
- The loop runs until `n//2` (integer division). This ensures that we are pairing up the first and last elements in the array and processing them.
## 3. **Concatenate and sum**
```python
concatenation_value += int(str(nums[i]) + str(nums[n - 1 - i]))
```
- For each pair, we concatenate `nums[i]` and `nums[n-1-i]` as strings, convert the result to an integer, and add it to `concatenation_value`.
## 4. **Handle the middle element for odd-length arrays**
```python
if n % 2 != 0:
concatenation_value += int(nums[n // 2])
```
- If the length of `nums` is odd, there will be one element left in the middle after pairing the first and last elements. This element is added to the `concatenation_value`.
## 5. **Return the final result**
```python
return concatenation_value
```
- The final result is returned after all operations.
# **Code 1**
```python
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
n = len(nums)
concatenation_value = 0
for i in range(n//2):
concatenation_value += int(str(nums[i]) + str(nums[n-1-i]))
if n % 2 != 0:
concatenation_value += int(nums[n//2])
return concatenation_value
```
---
---
# **Step-by-Step Solution Explanation - Code 2**
## 1. **Initialize variables**
- `n = len(nums)` gives the length of the array.
- `left = 0` and `right = n - 1` are initialized to point to the first and last elements of the array, respectively.
- `concatenation_value = 0` is initialized to accumulate the result.
## 2. **Convert elements to strings**
```python
str_nums = [str(i) for i in nums]
```
- Convert each number in the `nums` list to a string for easy concatenation.
## 3. **Loop through the array**
```python
while left < right:
```
- The loop runs as long as the `left` pointer is less than the `right` pointer.
- For each pair of elements at `left` and `right`, we concatenate them as strings, convert the result to an integer, and add it to `concatenation_value`.
## 4. **Move the pointers**
```python
left += 1
right -= 1
```
- After processing a pair, we move the `left` pointer one step right and the `right` pointer one step left to process the next pair.
## 5. **Handle the middle element for odd-length arrays**
```python
if left == right:
concatenation_value += int(str_nums[left])
```
- If the length of `nums` is odd, the `left` pointer and `right` pointer will meet at the middle element. This element is added to `concatenation_value`.
## 6. **Return the result**
```python
return concatenation_value
```
- Return the final accumulated `concatenation_value`.
# Code 2
```python3 []
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
n = len(nums)
left = 0
right = n-1
concatenation_value = 0
str_nums = [str(i) for i in nums]
while left < right:
concatenation_value += int(str_nums[left] + str_nums[right])
left += 1
right -= 1
if left == right:
concatenation_value += int(str_nums[left])
return concatenation_value
```
---
# **Time Complexity**
- Both `code1` and `code2` iterate over the array once, performing constant-time operations for each element. Thus, the time complexity is **O(n)**, where `n` is the length of the array.
---
# If you find my solution helpful, Do Upvote 😀
---
| 2 | 0 | ['Array', 'Two Pointers', 'Simulation', 'Python3'] | 0 |
find-the-array-concatenation-value | to_string() ans stoi() jindabad ! :D handle size even odd utna hee bas :D | to_string-ans-stoi-jindabad-d-handle-siz-2c1w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yesyesem | NORMAL | 2024-08-30T18:35:28.342275+00:00 | 2024-08-30T18:35:28.342348+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long ans=0;\n int n=nums.size();\n\n for(int i=0;i<n/2;i++)\n {\n string s=to_string(nums[i]);\n string k=to_string(nums[n-1-i]);\n\n string o=s+k;\n long long num=stoi(o);\n ans+=num;\n }\n if(n%2!=0)\n {\n ans+=nums[n/2];\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Easy Java Solution || Beginner Friendly || String Builder | easy-java-solution-beginner-friendly-str-a89h | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | anikets101 | NORMAL | 2024-04-21T14:20:52.457952+00:00 | 2024-04-21T14:20:52.457986+00:00 | 31 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long res = 0L;\n StringBuilder sb = new StringBuilder();\n int i = 0;\n int j = nums.length - 1;\n while(j >= i){\n if(j == i){\n sb.append(nums[i]);\n }else{\n sb.append(nums[i]).append(nums[j]);\n }\n int temp = Integer.parseInt(sb.toString());\n sb.setLength(0);\n res += temp;\n j--;\n i++;\n }\n return res;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
find-the-array-concatenation-value | Dart code | dart-code-by-4khil_raj-b4bm | \n\nclass Solution {\n int findTheArrayConcVal(List<int> nums) {\n int sum=0;\n int i=0;\n int j=nums.length-1;\n if(nums.length==1){\n | 4khil_Raj | NORMAL | 2024-01-03T06:17:19.820470+00:00 | 2024-01-03T06:17:19.820502+00:00 | 26 | false | \n```\nclass Solution {\n int findTheArrayConcVal(List<int> nums) {\n int sum=0;\n int i=0;\n int j=nums.length-1;\n if(nums.length==1){\n return nums[0];\n }else{\n while(i<j){\n var num1=nums[i].toString();\n var nums2=nums[j].toString();\n int result=int.parse(num1+nums2);\n sum+=result;\n i++;j--;\n if(i==j){\n sum+=nums[i];\n }\n }\n }\n print(sum);return sum;\n }\n}\n``` | 2 | 0 | ['Dart'] | 0 |
find-the-array-concatenation-value | BEATS 100% | 2 PTR | EASY | EXPLAINED | beats-100-2-ptr-easy-explained-by-smt26-c276 | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition is simply to directly take two pointers and start concatnating the | SMT26 | NORMAL | 2023-12-21T13:26:29.784167+00:00 | 2023-12-21T13:26:29.784197+00:00 | 23 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is simply to directly take two pointers and start concatnating the numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. As per the constraints for easy concatenation we will use strings rather than making the number.\n2. Then we will keep adding that number till the loop runs.\n3. In last check condition for odd elements and add it to concVal;\n4. Return concVal.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n(log(a)+log(b)))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(n(log(a)+log(b)))\n\n# Code\n```\nclass Solution {\npublic:\n int concatenate(int& a,int& b){\n string s=to_string(a)+to_string(b);\n return stoi(s);\n }\n long long findTheArrayConcVal(vector<int>& nums) {\n long long concVal=0;\n int i=0;\n int j=nums.size()-1;\n while(i<j){\n concVal+=concatenate(nums[i],nums[j]);\n i++;\n j--;\n }\n if (i==j){\n concVal+=nums[i];\n }\n return concVal;\n }\n};// HOPE YOU HAVE GOT IT!! :)\n```\n# PLEASE UPVOTE GUYS!!\n\n | 2 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | ❇ find-array-concatenation👌 🏆O(N)❤️ Javascript❤️ Memory👀95.45%🕕 Meaningful Vars✍️ 🔴🔥 ✅ 👉 💪🙏 | find-array-concatenation-on-javascript-m-awy1 | Time Complexity: O(N)\nSpace Complexity: O(1)\n\nvar findTheArrayConcVal = function(nums) {\n let store = 0;\n if (nums.length % 2 === 0) {\n for ( | anurag-sindhu | NORMAL | 2023-09-11T02:42:07.014287+00:00 | 2023-09-11T02:42:07.014318+00:00 | 256 | false | Time Complexity: O(N)\nSpace Complexity: O(1)\n```\nvar findTheArrayConcVal = function(nums) {\n let store = 0;\n if (nums.length % 2 === 0) {\n for (let index = 0; index < nums.length / 2; index++) {\n store += parseInt(`${nums[index]}${nums[nums.length - index - 1]}`);\n }\n } else {\n for (let index = 0; index < parseInt(nums.length / 2); index++) {\n store += parseInt(`${nums[index]}${nums[nums.length - index - 1]}`);\n }\n store += nums[Math.floor(nums.length / 2)];\n }\n return store;\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
find-the-array-concatenation-value | Easy Python solution ||runtime 96.19% | easy-python-solution-runtime-9619-by-lal-awd9 | \n\n# Code\n\nclass Solution(object):\n def findTheArrayConcVal(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n | Lalithkiran | NORMAL | 2023-03-17T13:51:36.632232+00:00 | 2023-03-17T13:51:36.632267+00:00 | 110 | false | \n\n# Code\n```\nclass Solution(object):\n def findTheArrayConcVal(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n sm=0\n i=0\n j=len(nums)-1\n if len(nums)%2!=0:sm+=nums[(i+j)//2]\n while i<j:\n sm+=int(str(nums[i])+str(nums[j]))\n i+=1\n j-=1\n return sm\n\n \n``` | 2 | 0 | ['Array', 'Two Pointers', 'Simulation', 'Python'] | 0 |
find-the-array-concatenation-value | Easy Java Solution | easy-java-solution-by-agdarshit19-oxmd | \n\n# Code\n\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long sum = 0;\n int i = 0;\n int j = nums.length - 1;\n | agdarshit19 | NORMAL | 2023-03-15T10:22:08.667020+00:00 | 2023-03-15T10:22:08.667068+00:00 | 688 | false | \n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long sum = 0;\n int i = 0;\n int j = nums.length - 1;\n while(i <= j)\n {\n String s = Long.toString(nums[i]);\n String st = Long.toString(nums[j]);\n s = s + st;\n if(i == j)\n {\n sum += nums[i];\n } \n else\n {\n sum = sum + Long.parseLong(s);\n System.out.println(sum);\n }\n i++;\n j--;\n }\n return sum;\n\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | Efficiently Concatenating and Summing Integers in JavaScript with two Approaches | efficiently-concatenating-and-summing-in-5yd2 | \n# Algorithm 1: Using String Conversion\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findTheArrayConcVal = function(nums) {\n let ans = | astiksarathe | NORMAL | 2023-02-24T06:23:18.107343+00:00 | 2023-02-24T06:23:18.107382+00:00 | 211 | false | \n# Algorithm 1: Using String Conversion\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findTheArrayConcVal = function(nums) {\n let ans = 0;\n let left = 0, right = nums.length-1;\n while(left <= right){\n if(left !== right){\n let n = countDigits(nums[left]);\n let m = countDigits(nums[right]);\n ans += nums[left] * Math.pow(10, m) + nums[right];\n }else{\n ans += nums[left];\n }\n left++, right--;\n }\n\n return ans;\n};\n\nfunction countDigits(num) {\n let count = 0;\n while (num !== 0) {\n num = Math.floor(num / 10);\n count++;\n }\n return count;\n}\n\n```\n# Algorithm 2: Using Math\n```\nvar findTheArrayConcVal = function(nums) {\n let ans = 0;\n let left = 0, right = nums.length-1;\n while(left <= right){\n if(left !== right){\n let strNum = nums[left].toString() + nums[right].toString()\n let num = parseInt(strNum)\n ans += num;\n }else{\n ans +=nums[left];\n }\n left++, right--;\n }\n\n return ans;\n};\n``` | 2 | 0 | ['Two Pointers', 'TypeScript', 'JavaScript'] | 1 |
find-the-array-concatenation-value | Java 100% faster solution | java-100-faster-solution-by-avadarshverm-s0jh | \n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O | avadarshverma737 | NORMAL | 2023-02-14T05:28:42.339080+00:00 | 2023-02-14T05:28:42.339131+00:00 | 638 | false | \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n \n long res = 0;\n int i = 0;\n int j= nums.length-1;\n \n while(i<j){\n int num = concatenate(nums[i++],nums[j--]);\n res += num;\n }\n if((nums.length&1) != 0){\n res += nums[i];\n }\n return res;\n }\n private int concatenate(int x,int y){\n return Integer.parseInt(String.valueOf(x)+String.valueOf(y));\n }\n}\n``` | 2 | 0 | ['String', 'Bit Manipulation', 'Java'] | 0 |
find-the-array-concatenation-value | Simple and easy Array | simple-and-easy-array-by-ayesha__19-rlf4 | \nclass Solution\n{\npublic:\n int concat(int a, int b)\n {\n string s1 = to_string(a);\n string s2 = to_string(b);\n string s = s1 + | ayesha__19__ | NORMAL | 2023-02-12T09:54:28.050439+00:00 | 2023-02-12T09:54:28.050478+00:00 | 26 | false | ```\nclass Solution\n{\npublic:\n int concat(int a, int b)\n {\n string s1 = to_string(a);\n string s2 = to_string(b);\n string s = s1 + s2;\n int c = stoi(s);\n return c;\n }\n long long findTheArrayConcVal(vector<int> &nums)\n {\n long long ans = 0;\n int n = nums.size();\n int start = 0, end = n - 1;\n while (start < end)\n {\n int x = concat(nums[start], nums[end]);\n ans += x;\n start++;\n end--;\n }\n if (n % 2 != 0)\n {\n ans += nums[n / 2];\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Array', 'Two Pointers', 'C++'] | 0 |
find-the-array-concatenation-value | CPP | Easy solution with string conversion | cpp-easy-solution-with-string-conversion-fnvx | \nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int n=nums.size();double ans=0;\n for(int i=0;i<n/2;i++){\n | sanketkadam143 | NORMAL | 2023-02-12T06:41:52.069407+00:00 | 2023-02-12T06:41:52.069441+00:00 | 229 | false | ```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int n=nums.size();double ans=0;\n for(int i=0;i<n/2;i++){\n string res="";\n res+=to_string(nums[i])+to_string(nums[n-i-1]);\n ans+=stoi(res); \n }\n if(n % 2 == 1){\n ans += nums[n/2];\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['String'] | 2 |
find-the-array-concatenation-value | Java | easy to understand | java-easy-to-understand-by-venkat089-jqed | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Venkat089 | NORMAL | 2023-02-12T04:05:00.056847+00:00 | 2023-02-12T04:05:00.056885+00:00 | 544 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long res=0;\n if(nums.length==1)return (long)nums[0];\n for(int i=0;i<nums.length/2;i++)\n {\n String str=nums[i]+""+nums[nums.length-i-1];\n res+=Long.parseLong(str);\n }\n if(nums.length%2!=0)res+=nums[nums.length/2];\n return res;\n \n \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | Python Solution easy to understand || super easy solution | python-solution-easy-to-understand-super-3sdw | \nclass Solution:\n def findTheArrayConcVal(self, num: List[int]) -> int:\n\t\t# to store final sum\n ans = 0\n\t\t# traverse the num array untill its | mohitsatija | NORMAL | 2023-02-12T04:04:14.443096+00:00 | 2023-02-12T04:04:14.443148+00:00 | 205 | false | ```\nclass Solution:\n def findTheArrayConcVal(self, num: List[int]) -> int:\n\t\t# to store final sum\n ans = 0\n\t\t# traverse the num array untill its empty\n while num:\n\t\t\t# pop the first element out convert it to string\n p = str(num.pop(0))\n q = ""\n\t\t\t\n\t\t\t# if array is non empty pop the last element out\n if num:\n q=str(num.pop())\n\t\t\t\n\t\t\t# concate the string and add it to final answer\n ans += int(p+q)\n return ans\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
find-the-array-concatenation-value | Easy Solution in java| O(N) time | easy-solution-in-java-on-time-by-utkarsh-qysq | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Utkarsh172 | NORMAL | 2023-02-12T04:03:39.758530+00:00 | 2023-02-12T04:04:41.839643+00:00 | 82 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n int j = nums.length-1;\n ArrayList<Integer> k = new ArrayList<>();\n if (nums.length%2==0) {\n for (int i = 0; i < nums.length / 2; i++) {\n\n String n = Integer.toString(nums[i]);\n String m = Integer.toString(nums[j]);\n j--;\n k.add(Integer.valueOf(n + m));\n }\n }\n else{\n for (int i = 0; i < nums.length / 2; i++) {\n\n String n = Integer.toString(nums[i]);\n String m = Integer.toString(nums[j]);\n j--;\n k.add(Integer.valueOf(n + m));\n }\n k.add(nums[nums.length/2]);\n }\n long sum = 0;\n for (int i = 0; i < k.size(); i++) {\n sum+=k.get(i);\n }\n\n return sum;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | [Java] Simple two pointers solution | java-simple-two-pointers-solution-by-0x4-qptd | Intuition\n Describe your first thoughts on how to solve this problem. \nJust follow the steps in the problem.\n\n# Approach\n Describe your approach to solving | 0x4c0de | NORMAL | 2023-02-12T04:03:09.216289+00:00 | 2023-02-12T04:03:49.985378+00:00 | 355 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust follow the steps in the problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse two pointers to mark the first and last number.\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n long result = 0;\n int left = 0;\n int right = nums.length - 1;\n while (left <= right) {\n if (left == right) {\n result += nums[left];\n } else {\n long shift = 1;\n int num = nums[right];\n while (num != 0) {\n shift *= 10;\n num /= 10;\n }\n\n result += shift * nums[left] + nums[right];\n }\n right--;\n left++;\n }\n\n return result;\n }\n}\n\n``` | 2 | 0 | ['Two Pointers', 'Java'] | 0 |
find-the-array-concatenation-value | leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3 and Beats 28.62% with Java | leetcodedaybyday-beats-100-with-c-and-be-iibg | IntuitionWe need to compute the "concatenation value" of an array by pairing numbers from both ends and concatenating them as strings before summing their numer | tuanlong1106 | NORMAL | 2025-02-22T08:46:17.121896+00:00 | 2025-02-22T08:46:17.121896+00:00 | 90 | false | # Intuition
We need to compute the "concatenation value" of an array by pairing numbers from both ends and concatenating them as strings before summing their numeric values.
# Approach
1. **Two-pointer technique**:
- Use two pointers (`left` and `right`), where `left` starts from the beginning and `right` starts from the end of the array.
- Move towards the center while pairing elements.
2. **Concatenation and conversion**:
- Convert each pair of elements into strings, concatenate them, and convert back to an integer before adding to the sum.
- If there's a middle element (odd length array), add it separately.
# Complexity
- **Time Complexity:** $$O(n)$$ (We iterate through the array once)
- **Space Complexity:** $$O(1)$$ (Only a few extra variables are used)
# Code
```cpp []
class Solution {
public:
long long findTheArrayConcVal(vector<int>& nums) {
long long total = 0;
int n = nums.size();
for(int i = 0, j = n - 1; i <= j; i++, j--){
if (i == j){
total += nums[i];
} else {
int concat = stoi(to_string(nums[i]) + to_string(nums[j]));
total += concat;
}
}
return total;
}
};
```
```java []
class Solution {
public long findTheArrayConcVal(int[] nums) {
long total = 0;
int n = nums.length;
for(int i = 0, j = n - 1; i <= j; i++, j--){
if (i == j){
total += nums[i];
} else {
long concat = Long.parseLong(nums[i] + "" + nums[j]);
total += concat;
}
}
return total;
}
}
```
```python3 []
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
total = 0
while left < right:
total += int(str(nums[left]) + str(nums[right]))
left += 1
right -= 1
if left == right:
total += nums[left]
return total
```
| 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++', 'Java', 'Python3'] | 0 |
find-the-array-concatenation-value | C++ 100% two indexes | c-100-two-indexes-by-michelusa-i5ya | Approach\nUse left and right indexes to iterate thtough nums.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\ncpp []\nclass So | michelusa | NORMAL | 2024-11-28T15:43:58.337102+00:00 | 2024-11-28T15:43:58.337149+00:00 | 39 | false | # Approach\nUse left and right indexes to iterate thtough nums.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long findTheArrayConcVal(const vector<int>& nums) const {\n if (nums.size() == 1) {\n return nums.front();\n }\n long long sum = 0;\n for (size_t left = 0, right = nums.size() - 1; left <= right; ++left, --right) {\n const std::string tmp = (left == right) ? std::to_string(nums[left]) : std::to_string(nums[left]) + std::to_string(nums[right]);\n sum += std::stoi(tmp);\n }\n return sum;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Easy solution with step by step | easy-solution-with-step-by-step-by-shamn-adif | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | shamnad_skr | NORMAL | 2024-11-15T19:22:27.613857+00:00 | 2024-11-15T19:22:27.613880+00:00 | 39 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findTheArrayConcVal = function(nums) {\n\n let resultValue = 0;\n\n while(nums.length > 0 ){\n\n if(nums.length > 1){\n\n const first = nums.shift().toString()\n const last = nums.pop().toString()\n\n resultValue += Number(first+last);\n }else{\n resultValue += nums.pop()\n }\n\n}\n\nreturn resultValue;\n \n};\n``` | 1 | 0 | ['TypeScript', 'JavaScript'] | 1 |
find-the-array-concatenation-value | Easy and direct solution... | easy-and-direct-solution-by-manyaagargg-zem9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | manyaagargg | NORMAL | 2024-07-30T15:59:04.302444+00:00 | 2024-07-30T15:59:04.302481+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long ans=0;\n int i=0; int j = nums.size()-1;\n while(i<j){\n string str1= to_string(nums[i]);\n string str2= to_string(nums[j]);\n string str = str1 + str2;\n long long help = stoi(str);\n ans+=help;\n i++;\n j--;\n }\n if(i==j){\n // string str2= to_string(nums[j]);\n // string str= str2;\n // long long help = stoi(str);\n ans+=nums[j];\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | SIMPLE TWO-POINTER C++ SOLUTION | simple-two-pointer-c-solution-by-jeffrin-56u2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Jeffrin2005 | NORMAL | 2024-07-20T13:10:33.562923+00:00 | 2024-07-20T13:10:33.562955+00:00 | 23 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\n#define ll long long \nclass Solution {\npublic:\n ll findTheArrayConcVal(vector<int>& nums) {\n ll n = nums.size();\n ll ans = 0;\n ll i = 0;\n ll j = n - 1;\n while (i < j){\n string s =to_string(nums[i]) +to_string(nums[j]); // concatenating num[i] and num[j]\n ans+=stoll(s); // Convert the concatenated string back to a int(long long) and add to ans.\n i++; \n j--; \n }\n if(i == j) ans+=nums[i]; // If there\'s one element left in the middle, add it to ans.\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Two Pointer || 83% T.C || 67% S.C || CPP | two-pointer-83-tc-67-sc-cpp-by-ganesh_ag-zo9x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Ganesh_ag10 | NORMAL | 2024-04-22T14:24:26.185257+00:00 | 2024-04-22T14:24:26.185283+00:00 | 34 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n long long result = 0;\n int l = 0, r = nums.size() - 1;\n while(l <= r){\n if(l == r){\n result += nums[l]; \n break;\n }\n result += stoi(to_string(nums[l++]) + to_string(nums[r--]));\n }\n\n return result;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | ✅ Laconic Two Pointers | laconic-two-pointers-by-eleev-5tyo | \n\n# Solution\nswift\nstruct Solution {\n @_optimize(speed)\n consuming func findTheArrayConcVal(_ nums: [Int]) -> Int {\n let n = nums.count\n | eleev | NORMAL | 2024-03-28T06:23:55.243357+00:00 | 2024-03-28T06:25:39.013853+00:00 | 2 | false | \n\n# Solution\n```swift\nstruct Solution {\n @_optimize(speed)\n consuming func findTheArrayConcVal(_ nums: [Int]) -> Int {\n let n = nums.count\n var concat = 0\n\n for left in nums.indices[..<(n >> 1 + n & 0b1)] {\n let right = n - left - 1\n concat += left == right ? nums[left] : nums[left] ++ nums[right]\n }\n return concat\n }\n}\n\nextension FixedWidthInteger {\n func concatenating(with value: Self) -> Self {\n Self.concatenating(self, with: value) + value\n }\n\n static func concatenating(_ rhs: Self, with lhs: Self) -> Self {\n lhs / 10 == 0 ? rhs * 10 : concatenating(rhs * 10, with: lhs / 10)\n }\n}\n\ninfix operator ++: AdditionPrecedence\n\nfunc ++ <T: FixedWidthInteger>(left: T, right: T) -> T {\n left.concatenating(with: right)\n}\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Swift', 'Simulation'] | 0 |
find-the-array-concatenation-value | Simple Java Solution 💡 | simple-java-solution-by-keerthivarmank-a8vi | Intuition\n\nThe provided Java function findTheArrayConcVal aims to calculate the concatenation value of an array of integers. The concatenation value is obtain | KeerthiVarmanK | NORMAL | 2024-02-12T14:38:20.494764+00:00 | 2024-02-12T14:38:20.494792+00:00 | 51 | false | # Intuition\n\nThe provided Java function findTheArrayConcVal aims to calculate the concatenation value of an array of integers. The concatenation value is obtained by concatenating each pair of integers from the array, where the integers are taken alternately from the beginning and end of the array.\n\n# Approach\n\n1. Initialization:\n\n- Initialize two pointers left and right at the beginning and end of the array, respectively.\n- Initialize a variable total to store the cumulative concatenation value.\n2. Loop:\n\n- Iterate through the array while left pointer is less than right.\nFor each iteration, concatenate the integers at positions left and right.\n- Increment left and decrement right to move towards the center of the array.\n3. Handling Odd Length Array:\n\n- If the length of the array is odd, there will be one element left at the center after the loop ends. Add this element to the total.\n4. Return Concatenation Value: Return the total concatenation value.\n\n# Complexity\n**Time complexity**:\n\n- The loop iterates through half of the array\'s length, so it performs O(n/2) concatenations, where n is the length of the input array.\n- Additionally, converting integers to strings and parsing them back to long integers has a time complexity proportional to the number of digits in the integers, but it doesn\'t significantly affect the overall time complexity.\n- Therefore, the time complexity is O(n) where n is the length of the input array.\n\n**Space complexity**:\n\n- The function uses a constant amount of extra space for variables (left, right, total, conVal), regardless of the size of the input array.\n- Therefore, the space complexity is O(1), constant space complexity.\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n int left = 0;\n int right = nums.length - 1;\n long total = 0;\n while(left < right){\n String conVal = String.valueOf(nums[left]) + String.valueOf(nums[right]);\n total += Long.parseLong(conVal);\n left++;\n right--;\n }\n return (nums.length % 2 == 0) ? total : total + Long.valueOf(nums[left]);\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | Simple solution | simple-solution-by-muhmdshanoob-z811 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | muhmdshanoob | NORMAL | 2024-01-03T05:42:59.934187+00:00 | 2024-01-03T05:42:59.934260+00:00 | 111 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findTheArrayConcVal = function(nums) {\n concatenatedSum =0;\n\n while(nums.length > 1){\n concatenatedSum += Number(nums[0].toString() + nums[nums.length-1].toString());\n \n nums.shift();\n nums.pop();\n }\n\n if(nums.length === 1){\n concatenatedSum += nums[0];\n }\n\n return concatenatedSum;\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
find-the-array-concatenation-value | Java .. Simple Approach | java-simple-approach-by-anoopchaudhary1-glcb | Code\n\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n List<String> list = new ArrayList<>();\n int l = 0;\n int r= | Anoopchaudhary1 | NORMAL | 2023-12-11T05:48:14.672543+00:00 | 2023-12-11T05:48:14.672576+00:00 | 31 | false | # Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n List<String> list = new ArrayList<>();\n int l = 0;\n int r= nums.length-1;\n while(l<=r){\n if(l != r){\n list.add(nums[l]+""+nums[r]+"");\n l++;\n r--;\n }\n else{\n list.add(nums[l]+"");\n l++;\n r--;\n }\n }\n long ans =0;\n for(String s : list){\n ans = ans+Long.parseLong(s);\n }\n \n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | java 1 ms | java-1-ms-by-susahin80-goic | Consider 12 and 123 as pair, for this pair we first find the length of the second num 123 as 3. Math.pow(10, 3) => gives 1000.\nWe multiply this 1000 with the f | susahin80 | NORMAL | 2023-11-15T11:47:18.808025+00:00 | 2023-11-15T11:47:18.808044+00:00 | 28 | false | Consider 12 and 123 as pair, for this pair we first find the length of the second num 123 as 3. Math.pow(10, 3) => gives 1000.\nWe multiply this 1000 with the first num 12 and get 12000 and as last step we add second num to this, giving 12123. We apply this logic in loop.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n$O(1)\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n int n = nums.length;\n if (n == 1) return nums[0];\n long result = 0;\n int l = 0;\n int r = n - 1;\n while (l < r) {\n int lenRight = lengthOfNumber(nums[r]);\n result += (long) Math.pow(10, lenRight) * nums[l++] + nums[r--];\n }\n if (l == r) {\n result += nums[l];\n }\n return result;\n }\n\n private int lengthOfNumber(int num) {\n int l = 0;\n\n while (num != 0)\n {\n num /= 10;\n l++;\n }\n\n return l;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | ✅ Two-liner, 23ms Beats 100.00% | two-liner-23ms-beats-10000-by-swifterswi-scgl | Solution 1 \u2014 Two-liner\n\n24ms Beats 94.44%\n\nswift\nfunc findTheArrayConcVal(_ nums: [Int], _ i: Int = 0) -> Int {\n guard i != nums.count / 2 else { | swifterswifty | NORMAL | 2023-10-27T14:14:08.522503+00:00 | 2023-10-27T14:33:25.475154+00:00 | 49 | false | # Solution 1 \u2014 Two-liner\n\n24ms Beats 94.44%\n\n```swift\nfunc findTheArrayConcVal(_ nums: [Int], _ i: Int = 0) -> Int {\n guard i != nums.count / 2 else { return nums.count % 2 == 0 ? 0 : nums[i] }\n return Int(String(nums[i]) + String(nums[nums.count - 1 - i]))! + findTheArrayConcVal(nums, i + 1)\n}\n```\n\n# Solution 2\n\n23ms Beats 100.00%\n\n```swift\nfunc findTheArrayConcVal(_ nums: [Int], _ i: Int = 0) -> Int {\n guard i != nums.count / 2 else { return nums.count % 2 == 0 ? 0 : nums[i] }\n return concatenated(nums[i], nums[nums.count - 1 - i]) + findTheArrayConcVal(nums, i + 1)\n}\n\nprivate func concatenated(_ n: Int, _ m: Int) -> Int {\n concatenationHead(n, m) + m\n}\n\nprivate func concatenationHead(_ n: Int, _ m: Int) -> Int {\n m / 10 == 0 ? n * 10 : concatenationHead(n * 10, m / 10)\n}\n``` | 1 | 0 | ['Recursion', 'Swift'] | 1 |
find-the-array-concatenation-value | Simple + Understandable; | simple-understandable-by-rohit_pawar-wrns | \n# Code\n\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n vector<string> s;\n int sz = nums.size();\n | rohit_pawar | NORMAL | 2023-08-15T16:31:24.101061+00:00 | 2023-08-15T16:31:24.101091+00:00 | 7 | false | \n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n vector<string> s;\n int sz = nums.size();\n if(sz%2==0)sz=sz/2;\n else sz = (sz/2)+1;\n for(int i = 0; i < sz; i++){\n if(nums.size()==1)s.push_back(to_string(nums[0]));\n else{\n string first = to_string(nums[0]);\n string last = to_string(nums[nums.size()-1]);\n\n s.push_back(first+last); \n\n nums.erase(nums.begin());\n nums.pop_back();\n }\n }\n\n long long int ans = 0;\n for(int i = 0; i < s.size(); i++){\n ans += stoi(s[i]);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Java 0ms beats 100% | java-0ms-beats-100-by-texastim-7rd2 | \n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n\n | texastim | NORMAL | 2023-08-03T22:16:30.751216+00:00 | 2023-08-03T22:17:14.901373+00:00 | 15 | false | \n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n\n long sum = 0; // what we\'ll return\n int idxLeft = 0;\n int idxRight = nums.length - 1;\n\n while (idxLeft < idxRight) {\n sum += getConcatenationValue(nums[idxLeft], nums[idxRight]);\n ++idxLeft;\n --idxRight;\n }\n\n if (idxLeft == idxRight) {\n sum += nums[idxLeft];\n }\n\n return sum;\n }\n\n private long getConcatenationValue(int leftVal, int rightVal) {\n\n long left = leftVal;\n long right = rightVal;\n\n // right == 10000\n if (right == 10000) {\n return left * 100000L + right;\n }\n\n // 9999 >= right >= 1000\n if (right >= 1000) {\n return left * 10000L + right;\n }\n\n // 999 >= right >= 100\n if (right >= 100) {\n return left * 1000L + right;\n }\n \n // 99 >= right >= 10\n if (right >= 10) { \n return left * 100L + right;\n }\n\n // 9 >= right >= 1\n return left * 10L + right;\n }\n\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-the-array-concatenation-value | Array Concatenation Value | array-concatenation-value-by-shaunak5432-utvm | Approach\n Describe your approach to solving the problem. \nWe need to iterate on the list from the start and reverse from the end. We will only interate half o | Shaunak54323 | NORMAL | 2023-04-10T14:28:13.595830+00:00 | 2023-04-10T18:49:12.804132+00:00 | 20 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe need to iterate on the list from the start and reverse from the end. We will only interate half of the loop. Then we will concatinate ```i```th and ```n - i - 1```th element by converting it into string, adding it and again converting it to the integer. We will then add it to our final result. \n\nThis will only go if the total number of elements in the list are even. If the total number of elements are odd then we will add the middle element on our final answer \n\n# Complexity\n- Time complexity: O(n/2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: list[int]) -> int:\n ans = 0\n length = len(nums)\n if length == 1:\n return nums[0]\n \n for i in range(int(length / 2)):\n ans += int(str(nums[i]) + str(nums[length - i - 1]))\n if length % 2 == 1:\n ans += nums[int(length / 2)]\n \n return ans\n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
find-the-array-concatenation-value | Two pointer --> Beginner friendly C++ code | two-pointer-beginner-friendly-c-code-by-w68fb | Intuition\n Describe your first thoughts on how to solve this problem. \nTwo pointer concept need is needed to be used. Keep pointer \'i\' in the begining and \ | sunny_6289 | NORMAL | 2023-04-09T09:09:22.562550+00:00 | 2023-04-09T09:09:22.562586+00:00 | 29 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTwo pointer concept need is needed to be used. Keep pointer \'i\' in the begining and \'j\' in the end.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIncrease i and decrease j as long as they don\'t cross each other. Convert them into strings, perform string concatination then convert them into interger and then add it to the concatination value \' sum \'\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int i=0;\n int j=nums.size()-1;\n long long sum=0;\n while(i<=j){\n if(i==j){\n sum+=nums[i];\n i++;\n j--;\n }else{\n sum+=stoi(to_string(nums[i])+to_string(nums[j]));\n i++;\n j--;\n }\n }\n return sum;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Find the Array Concatenation Value Solution in C++ | find-the-array-concatenation-value-solut-ttxb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | The_Kunal_Singh | NORMAL | 2023-03-22T14:50:16.632906+00:00 | 2023-03-22T14:50:16.632942+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n long long findTheArrayConcVal(vector<int>& nums) {\n int i;\n long long int ans=0;\n string s="";\n for(i=0 ; i<nums.size()/2 ; i++)\n {\n s = to_string(nums[i]) + to_string(nums[nums.size()-i-1]);\n ans += stoi(s);\n }\n if(nums.size()%2==1)\n {\n ans += nums[nums.size()/2];\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-array-concatenation-value | Simple java solution | simple-java-solution-by-prithviraj26-62bx | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | prithviraj26 | NORMAL | 2023-03-20T08:46:03.695550+00:00 | 2023-03-20T08:46:03.695579+00:00 | 250 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n\n# Code\n```\nclass Solution {\n public long findTheArrayConcVal(int[] nums) {\n String x="";\n ArrayList<String>a=new ArrayList<String>();\n int i=0,j=nums.length-1;\n while(i<=j)\n {\n if(i==j)\n {\n x+=String.valueOf(nums[i]);\n a.add(x);\n }\n else\n {\n x+=String.valueOf(nums[i]);\n x+=String.valueOf(nums[j]);\n a.add(x);\n }\n x="";\n i++;\n j--;\n \n }\n long ans=0;\n for(int k=0;k<a.size();k++)\n {\n ans+=Integer.parseInt(a.get(k));\n }\n return ans;\n }\n}\n```\n\n | 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'Java'] | 0 |
find-the-array-concatenation-value | Easy Solution Using While Loop in Python | easy-solution-using-while-loop-in-python-32xk | \n\n# Code\n\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n i=0\n c=0\n j=len(nums)-1\n while(i<=j): | sanchisinghal | NORMAL | 2023-03-15T10:23:30.087044+00:00 | 2023-03-15T10:23:30.087098+00:00 | 474 | false | \n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n i=0\n c=0\n j=len(nums)-1\n while(i<=j):\n if(i==j):\n c=c+nums[i]\n break\n s=str(nums[i])+str(nums[j])\n c=c+int(s)\n i=i+1\n j=j-1\n return c\n \n``` | 1 | 0 | ['Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.