This is a collection of common C++ classes and templates that we often use, and thus are perfect opportunities for interviewers to quiz on to see if the candidate is comfortable with the language, can write clean code, and is aware about the internals of the language.
Smart Pointers
General Smart Pointer
Problems with AutoPtr
:
- When passed to function by value, the pointer is moved to the function and the memory would be freed when the function returns. Thus in the original function, this can lead to a dangling pointer.
- This deletes using the non-array
delete
operator, and thus if the pointer was allocated usingnew[]
, it would lead to undefined behaviour.
Thus they were replaced by std::unique_ptr
, std::shared_ptr
, and std::weak_ptr
in C++11.
Unique Pointer
Shared Pointer
Hit Counter
Base Variant
You need to implement a HitCounter
class that supports the following operations:
HitCounter()
Initializes the object of the class.void hit(int timestamp)
Records a hit that happened at the given timestamp.int getHits(int timestamp)
Returns the number of hits in the past 5 minutes.
Each function accepts a timestamp
parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (i.e. the timestamp is monotonically increasing).
This function uses a deque
to store the hits, and a curCnt
to store the total number of hits. The removeOldHits
function is used to remove the hits that are older than 5 minutes. One salient feature of this implementation is that it does not store the hits for each second, but rather stores the number of hits at each second, and thus this implementation would gracefully handle the case when there are multiple hits at the same second. If the same was not a requirement, we could have used a queue
instead of a deque
to store the hits.
- Time Complexity:
hit
:getHits
:
Unordered Timestamps
Implement the same interface as above, but now the timestamps are not guaranteed to be in order.
-
Time Complexity:
hit
:getHits
:
where is the number of unique timestamps
Concurrent Hit Counter
Implement the same interface as above, but now the class needs to be thread-safe. You can assume that the threads would be calling the same in chronological order.
Infinite Timestamps in the Past
In this variant, we want the hit counter to be able to answer queries of all the time in the past, and the solution should use constant memory. Some inaccuracy is allowed in the answer. To handle the same, we would make use of buckets of size of powers of 2, so that the older buckets store more points and are updated less frequently.