Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views1 page

L

The document contains two code snippets: one for moving all zero values in an array to the end while maintaining the order of non-zero elements, and another for implementing an LRU (Least Recently Used) cache using an OrderedDict in Python. The LRUCache class allows for getting and putting key-value pairs while managing the cache size limit. The solution for moving zero values is implemented in C++ and the LRU cache in Python.

Uploaded by

Recovery Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

L

The document contains two code snippets: one for moving all zero values in an array to the end while maintaining the order of non-zero elements, and another for implementing an LRU (Least Recently Used) cache using an OrderedDict in Python. The LRUCache class allows for getting and putting key-value pairs while managing the cache size limit. The solution for moving zero values is implemented in C++ and the LRU cache in Python.

Uploaded by

Recovery Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

// // MOVE ZERO VALUES

using namespace std;

vector<int> solution(vector<int> arr) {


int pos = 0; // Pointer for the next non-zero position

// Move all non-zero elements to the front


for (int num : arr) {
if (num != 0) {
arr[pos] = num;
pos++;
}
}

// Fill the remaining positions with zeroes


for (int i = pos; i < arr.size(); i++) {
arr[i] = 0;
}

3. ///
from collections import OrderedDict

class LRUCache:
def __init__(self, limit: int):
self.cache = OrderedDict() # Initialize an ordered dictionary to maintain
the order of access
self.limit = limit # Set the cache size limit

def get(self, key: str) -> int:


if key not in self.cache:
return -1 # Return -1 if the key is not in the cache

# Move the accessed key to the end to mark it as recently used


self.cache.move_to_end(key)
return self.cache[key] # Return the value associated with the key

def put(self, key: str, value: int) -> None:


if key in self.cache:
# Update the value and move the key to the end to mark it as recently
used
self.cache.move_to_end(key)
self.cache[key] = value # Insert or update the key-value pair

if len(self.cache) > self.limit:


# Remove the least recently used item (the first item in OrderedDict)
self.cache.popitem(last=False)

return arr;
}

You might also like