
Real Interview Questions for the Software Engineer at MediaTek
NewInterview Q&A
Q&A-1What is the difference between pointers and references in C++?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
A pointer is a variable that holds an address. It can be null, it can be reseated to point elsewhere, and you dereference it with *. A reference is an alias bound at initialization to an existing object. It cannot be reseated, and it reads like the object itself. On a 64-bit target a pointer is normally 8 bytes. A reference has no size of its own: sizeof on a reference yields the size of the referent, so sizeof(int&) is 4. Implementations typically store a reference as an address internally, but that is not part of the type.
#include <cstdint>
#include <memory>
void bump(int* p) { // may be null
if (p) *p += 1;
}
void bumpRef(int& r) { // caller guarantees a live int
r += 1;
}
int main() {
int x = 10;
int y = 20;
int* p = &x;
int& r = x; // r aliases x, not a copy
bump(p); // x == 11
bumpRef(r); // x == 12
p = &y; // reseat: p now points at y
r = y; // assignment through reference: x = 20, r still aliases x
// int& bad; // ill-formed: a reference needs an initializer
// int& nullRef = *static_cast<int*>(nullptr); // compiles, UB on use
}The last two lines are the practical difference. A pointer can represent absence. A reference cannot, so passing int& is a promise that the caller has a real object. That promise is why references dominate function parameters for non-null inputs, and why a pointer is the honest type for an optional parameter.
| Property | Pointer | Reference |
|---|---|---|
| Null | Yes, nullptr | No, a null dereference can forge one, then use is undefined behavior |
| Reseat | Yes, p = &y | No, assignment writes through to the referent |
| Initialization | Optional | Mandatory at declaration |
| Arithmetic | p + 1, p[i] | None, operates on the object |
| Overloading | void f(int*) is distinct from void f(int&); calling with an object selects the reference, calling with &x or nullptr selects the pointer | Same, the overload set distinguishes address from object |
| Const and members | int* const p, const int* p, pointer to pointer | int&, const int&; no pointer to reference, no array of references |
| Size | 8 bytes on a typical 64-bit target | sizeof gives the referent size, for example sizeof(int&) is 4 |
Where each one bites
A dangling reference and a dangling pointer fail the same way, at runtime, with no diagnostic. Returning a reference to a local, or storing a reference in a struct whose referent dies first, compiles cleanly. The difference is detection: a pointer can be checked against nullptr. A reference gives you no check to write. Rule I use: never return a reference to an object you do not own, and never store a reference as a member unless lifetime is tied to the owner in the same aggregate.
Pointer arithmetic is the other sharp edge. p + 1 scales by sizeof(*p), which is convenient for buffers and a classic overflow source when p is near the end of an allocation. References remove that footgun because there is no address to increment.
Stack, heap, and smart pointers
On the MediaTek embedded side this matters because stack is small and heap fragmentation is a field failure. A raw pointer does not allocate. new allocates on the heap and returns a pointer, and the caller owns the matching delete. That manual pairing is where double-free and leak bugs live.
std::unique_ptr<T> is the default replacement. It is a pointer with a destructor that deletes the object, same size as a raw pointer (8 bytes), zero runtime cost, and it makes ownership transfer explicit with std::move. Use it when exactly one owner exists, which is most cases: a driver buffer handed from a producer to a consumer, a parsed config tree, a file handle wrapper.
std::shared_ptr<T> adds shared ownership with an atomic reference count in a separate control block. On libstdc++ that is typically 16 bytes for the pointer pair plus 16 bytes for the control block (two atomic counts), and every copy or destruction does an atomic increment or decrement. That cost is fine on a phone SoC and painful in a tight audio or modem path where you copy handles per frame. Use it only when ownership is genuinely shared and cycles are handled with weak_ptr. If you cannot name the second owner, you do not need shared_ptr.
| Type | Owners | Cost | Use when |
|---|---|---|---|
T* raw | Unclear, by convention | 8 bytes, no check | Non-owning view, C interop, optional parameter |
T& | Borrower, must outlive use | No own size, sizeof is the referent | Non-null input parameter, const T& for large read-only args |
unique_ptr<T> | Exactly one | 8 bytes, no atomic | Default owning pointer |
shared_ptr<T> | Many, counted | About 16 bytes plus control block, atomic ops | Shared cache, observer graph with weak_ptr back edges |
My default in a review: const T& for input, T* or std::optional<T> when absence is legal, unique_ptr for ownership, and shared_ptr only with a named second owner. That keeps null checks where null is meaningful and removes them where it is not.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2What is the difference between stack and heap memory, and when would you use each?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
Stack is automatic, scoped storage. The compiler lays out frames as a function is entered and tears them down on return. Heap is manual or managed storage you request at runtime and release yourself, or through a smart pointer. I put a value on the stack when its lifetime is the function call and its size is known at compile time. I put it on the heap when the size is only known at runtime, when it must outlive the function, or when it is shared across threads or components.
That rule comes from how the two regions are managed, not from speed folklore.
| Stack | Heap | |
|---|---|---|
| Allocation | Compiler, on call and return | Runtime call: malloc, new, make_unique |
| Lifetime | Ends when the scope or function exits | Ends when freed, or when the owning smart pointer dies |
| Size | Fixed at compile time for a plain array; overflow corrupts adjacent frames | Variable, chosen at runtime |
| Access | Direct, no pointer needed for a local | Through a pointer or reference |
| Failure mode | Overflow, silent corruption if unchecked | Fragmentation, leaks, use-after-free, double free |
| Typical limit | Per-thread, often 1 MB for a pthread, 8 MB for the Linux main thread | Whole process address space, in practice RAM plus swap on Linux, RAM only on most MediaTek Android devices |
Why the stack is fast and why it breaks
A stack frame is a pointer bump. The stack pointer moves down by the frame size, locals sit at fixed offsets, and return restores the old pointer. No allocator runs, no free list is searched. That is the real reason stack access is cheap, not a cache slogan.
The cost is a hard ceiling per thread. A recursive parser that uses 4 KB per frame will exhaust a 1 MB thread stack in about 256 frames. On Linux that usually ends in a segfault at the guard page. In a MediaTek modem or kernel context, where stacks are far smaller and there is no guard page to save you, the same overflow overwrites adjacent data and fails much later and much worse. I size frames deliberately: no large buffers, no variable length arrays of input-controlled size, and recursion depth bounded or moved to an explicit work queue.
// C++17, checked against g++ 13 on Linux x86-64
#include <cstdint>
#include <memory>
#include <vector>
void process_frame(const std::uint8_t* in, std::size_t len) {
std::uint8_t header[64]; // stack: fixed size, dies on return
header[0] = in[0];
// heap: size known only at runtime, must outlive this call
auto payload = std::make_unique<std::uint8_t[]>(len);
payload[0] = header[0];
// hand off ownership without a raw delete anywhere
send_to_driver(std::move(payload), len);
}Choosing heap ownership in C++
The report from candidates mentions pointers versus references and unique_ptr versus shared_ptr, and that is where heap mistakes actually happen in our codebase.
A raw pointer can point anywhere and can dangle. A reference must bind at declaration and cannot be reseated, which makes it a good parameter type for "read this, do not own it." Neither one owns memory.
For ownership I default to std::unique_ptr. It has sole ownership, costs nothing extra over a raw pointer, and makes the release point visible. std::shared_ptr adds a control block and an atomic reference count on every copy and destroy. I use it only when two owners genuinely share lifetime, for example a frame buffer handed from a camera HAL thread to a codec thread with no single clear owner. If I cannot name the second owner, shared_ptr is hiding a design problem.
Failure modes I watch for on constrained devices
Heap fragmentation is the one that bites on long-running MediaTek Android services. Repeated malloc and free of different sizes splits the arena. Total free memory can look healthy while no single contiguous block remains for a large allocation, and the allocation fails anyway. The fix is to allocate a few large pools up front, for example a ring buffer for audio or video frames, and reuse slots instead of allocating per frame.
Leaks are slower but just as fatal where there is no swap. A leak of 64 KB per handled message is invisible in a test and kills a service after a day of uptime. I check with AddressSanitizer in CI and with malloc_info or heap dumps on device, and I treat a growing resident set size with flat traffic as a leak until proven otherwise.
Use-after-free and double free are the other pair. They rarely crash at the fault. They corrupt a later allocation and crash in unrelated code, which is why I avoid raw new and delete entirely and let unique_ptr and containers own the lifetime. When a crash report points at the allocator, my first question is who freed it twice, not which allocator is slow.
So in practice: stack for small, fixed, short-lived values; heap for runtime-sized, long-lived, or shared data; unique_ptr as the default owner; shared_ptr only with a named second owner; and on embedded targets, pool the hot allocations instead of trusting the general allocator to stay tidy for months.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3When would you choose unique_ptr over shared_ptr?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
I default to unique_ptr and only reach for shared_ptr when ownership is genuinely shared. unique_ptr says one owner, transfer on move, delete on scope exit. That matches most firmware and driver code at MediaTek, where a HAL service, a camera pipeline, or a modem context has a single owner and teardown order matters. shared_ptr says the last owner out deletes, which is harder to reason about in a long-running daemon and costs an atomic increment on every copy.
The cost is concrete. On a 64-bit ARM build, unique_ptr is 8 bytes and a move is a pointer copy plus a null-out. shared_ptr is 16 bytes, usually allocates a separate control block unless make_shared is used, and every copy or destruction does an atomic refcount update. In a hot path that contends across threads, that atomic can cost tens of nanoseconds per operation and creates cache-line bouncing. In a memory-constrained BSP image, the extra allocation and the risk of a cycle leaking the object are the bigger problem.
// C++17, checked against libstdc++ / libc++ semantics
#include <memory>
#include <utility>
struct ICodec { // polymorphic base
virtual ~ICodec() = default; // virtual dtor is mandatory here
virtual int encode(const void* in, void* out) = 0;
};
class H264Codec final : public ICodec {
public:
int encode(const void* in, void* out) override { /* ... */ return 0; }
};
// Factory: caller owns the result, transfer is a move.
std::unique_ptr<ICodec> make_codec() {
return std::make_unique<H264Codec>();
}
// Shared only because two subsystems genuinely co-own the cache.
std::shared_ptr<CalibrationTable> g_calibration; // loaded once, read by ISP + AFNote the virtual destructor. unique_ptr<ICodec> will call the derived destructor only if ~ICodec is virtual. Without it, deleting through the base is undefined behaviour and in practice leaks the derived part. The same rule applies to shared_ptr, but the factory returning unique_ptr makes the single-owner intent visible at the call site.
| Situation | Choice | Why |
|---|---|---|
| --- | --- | --- |
Factory or new at one site | unique_ptr | One owner, move to the consumer |
| Pimpl, move-only member, RAII handle | unique_ptr with custom deleter | No copy, deterministic close |
| Async callback may outlive the creator | shared_ptr or weak_ptr capture | Lifetime extended explicitly |
| Cache or config read by several threads | shared_ptr<const T> | Immutable, shared ownership is real |
| Observer or parent back-pointer | weak_ptr | Breaks the cycle that would leak |
| Cycle A owns B, B owns A | unique_ptr one way, weak_ptr the other | shared_ptr both ways leaks |
When shared_ptr is the right call. Three cases come up in Android vendor code. First, an object is published to a cache or registry and multiple clients hold it with no single owner to pick. Second, a callback, timer, or binder thread captures the object and the creator cannot guarantee ordering. Third, a value is passed across a thread pool where copying a raw pointer would be unsafe. In each case I use make_shared, keep the pointee immutable after publication, and use weak_ptr for anything that only observes.
Failure modes I watch for. A cycle between two shared_ptr owners never reaches zero, so the object leaks silently until the process is killed. I break it with a weak_ptr on the back edge and check expired() in tests. A second failure is a custom resource, such as a driver handle or a FILE*-like vendor handle, where the default deleter is wrong. I pass a deleter that calls the close function exactly once, and I test that an exception path still closes it. A third failure is resetting a shared_ptr while another thread is reading through a raw pointer obtained from get(). That is a data race regardless of the smart pointer, and ThreadSanitizer catches it in a stress test.
My rule in review: if a reviewer cannot name the second owner, the code gets unique_ptr. If they can, shared_ptr with make_shared and a comment naming the owners. That keeps the common case cheap and makes the expensive case deliberate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4How do virtual methods and abstract classes work in C++?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
A virtual method is a member function the compiler dispatches through a per-object pointer to a per-class table, so the override that runs is chosen by the object's dynamic type, not the static type of the pointer or reference used to call it. An abstract class is a class with at least one pure virtual method, written = 0. It cannot be instantiated, and any derived class that does not override every pure virtual method stays abstract too.
In a MediaTek driver or HAL codebase I would use that for a hardware interface. The interface defines the contract, the concrete class binds it to one SoC or sensor, and upper layers program against the base pointer.
// C++17, Itanium ABI as used by GCC/Clang on ARM64 Linux/Android
#include <cstdint>
#include <memory>
class ISensor {
public:
virtual ~ISensor() = default; // virtual destructor, see below
virtual bool init(uint32_t rate_hz) = 0; // pure virtual: abstract
virtual bool read(int32_t& value) = 0; // pure virtual: abstract
};
class AccelSensor final : public ISensor {
public:
bool init(uint32_t rate_hz) override { /* program registers */ return true; }
bool read(int32_t& value) override { value = 42; return true; }
};
int main() {
std::unique_ptr<ISensor> s = std::make_unique<AccelSensor>();
s->init(100); // calls AccelSensor::init, not ISensor::init
int32_t v = 0;
s->read(v); // calls AccelSensor::read
}What the compiler actually emits
On a 64-bit ARM64 build, each polymorphic object carries one extra pointer, the vptr, 8 bytes, pointing to the vtable for its most-derived class. The vtable holds one function pointer per virtual method, plus entries for the destructor and type info. A virtual call loads the vptr, loads the slot, and calls through it. That is one extra load and an indirect branch compared with a direct call. It prevents inlining across the call unless the compiler can prove the dynamic type, for example when the object is created locally and never escapes.
| Call site | Static type | Dynamic type | Method run |
|---|---|---|---|
s->init(100) | ISensor* | AccelSensor | AccelSensor::init |
s->read(v) | ISensor* | AccelSensor | AccelSensor::read |
delete s | ISensor* | AccelSensor | AccelSensor::~AccelSensor, then ISensor::~ISensor |
Abstract classes and the rules that bite
A pure virtual method can still have a body, and a derived class can call it explicitly as ISensor::read(), but the class stays abstract until every pure virtual is overridden. You can hold pointers and references to an abstract type, pass it by value only by slicing, and you cannot declare a plain object of it or an array of it.
Three failure modes come up in review:
- Non-virtual destructor. If
~ISensor()is not virtual,deleteon a base pointer to a derived object is undefined behaviour. In practice the derived destructor never runs and resources leak. The fix isvirtual ~ISensor() = default;or a protected non-virtual destructor if deletion through the base should be banned. - Slicing.
void f(ISensor s)copies only theISensorsubobject. The vptr is reset to theISensorvtable, so virtual dispatch is lost. Pass by pointer or reference. - Multiple inheritance diamond. If
Ainherits virtually from a common base andBandCboth inherit fromA, a non-virtual diamond gives two base subobjects and ambiguous calls.class B : virtual public Ashares one subobject. That costs an extra offset adjustment on the call path and surprises people who expect a single vptr layout, so I keep driver interfaces single-inheritance and use composition for the second capability.
When I would not use it
For a hot path in firmware, say a 1 kHz interrupt handler or a per-sample DSP loop, I would avoid virtual dispatch and use a template with static polymorphism or a plain function pointer table I control. Templates give the compiler the concrete type at compile time, so calls inline and there is no vptr overhead. I would also skip virtual methods for types that must stay trivially copyable or be laid out exactly in shared memory, since adding a vptr changes size and layout. The trade is compile-time coupling: every new sensor needs a rebuild of the templated code, whereas a virtual interface lets a new shared library plug in without recompiling callers.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5What are the pitfalls of multiple inheritance in C++?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
Multiple inheritance in C++ is legal and sometimes useful for mixing interfaces, but it makes name lookup, object layout and construction order harder to reason about. The three pitfalls that bite in production code are the diamond, ambiguity, and fragile layout.
The diamond is the classic one. If B and C both inherit from A, and D inherits from both B and C, a plain D object contains two A subobjects. Calling a method defined only in A through D is ambiguous, and d.A::x and the two copies can diverge. Virtual inheritance fixes the duplication by sharing one A subobject, at a cost: every access to the virtual base goes through an offset stored in the vtable, construction order becomes less intuitive, and the class cannot be used as a simple POD type.
Ambiguity is broader than the diamond. If two bases each provide flush() or a member with the same name, an unqualified call on the derived object does not compile. You must qualify it, which couples callers to the inheritance graph. Adding a new base later can break existing code that compiled fine before, because a previously unambiguous name becomes ambiguous.
Layout is the third pitfall, and it matters in firmware and driver code where a class may be passed across a C boundary or a shared library. With multiple inheritance, the compiler inserts padding and adjusts this when converting a pointer to the second base. That offset is implementation defined. It is stable for one compiler and ABI, not portable across compilers, and it grows the object. A class with two polymorphic bases carries two vptrs.
// Checked against C++17 semantics (Itanium ABI on Linux/Clang and GCC).
struct Device { virtual ~Device() = default; virtual void reset() {} int id = 0; };
struct Sensor : virtual Device { void reset() override {} };
struct Radio : virtual Device { void reset() override {} };
struct Node : Sensor, Radio {};
Node n;
n.reset(); // OK: one shared Device subobject, most-derived override wins
Device* p = &n; // OK: unambiguous conversion to the virtual base
// Without `virtual` on Device, n.reset() and the conversion above are ambiguous.Worked trace: what changes with virtual inheritance
| Hierarchy | Device subobjects in Node | n.reset() | Device* p = &n |
|---|---|---|---|
Sensor : Device, Radio : Device | 2 | ambiguous, compile error | ambiguous, compile error |
Sensor : virtual Device, Radio : virtual Device | 1, shared | resolves to the most-derived override | unambiguous |
Construction order also surprises people. Bases are constructed in declaration order, not in the order they appear in the constructor initializer list, and a virtual base is constructed once, before any class that inherits from it, even if that class is not the most-derived one. If Device's constructor does work that assumes Sensor is already initialised, that assumption fails.
Failure modes I would name in the loop
- Ambiguous
dynamic_cast. Casting aNode*toDevice*works with virtual inheritance. Casting across two non-virtual copies, or to a non-virtual base that appears twice, is ill-formed or returns null depending on the path. In a driver dispatch table that means a cast silently fails at runtime instead of at compile time. - Slicing and duplicate state. Passing a
Nodeby value where aDeviceis expected copies only oneDevicesubobject. The other copy is lost, and the twoidfields in the original can already disagree. - Fragile base class. Adding a member function named
reset()to a new base can make every existing call site ambiguous. This is why large codebases restrict multiple inheritance to interface-like bases with pure virtual functions and no data members. - ABI breakage. Adding or reordering a base changes offsets and vtable layout. Any binary that stored a pointer to the second base, or serialised the object, breaks without a source change.
When I would use it, and when I would not
I would use multiple inheritance narrowly: a concrete class implementing two unrelated interfaces, for example a hardware block that is both a ClockSource and a PowerDomain, with no shared data and no diamond. I would prefer composition in most other cases. A member pointer or a std::unique_ptr to a collaborator gives the same reuse without ambiguous lookup, without pointer adjustment, and without forcing an is-a relationship that is not really true. If the design needs a shared base reached by two paths, virtual inheritance is the correct tool, but I would treat it as a design smell to be contained, not a pattern to spread. The test I apply is simple: if removing the second base forces me to qualify names at call sites or to think about offsets, the inheritance is doing work that composition would do more cheaply.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6How do vector and list differ, and how do map and unordered_map differ?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
vector is a contiguous array. list is a doubly linked list. map is a red-black tree keyed in sorted order. unordered_map is a hash table. Those four facts decide complexity, cache behaviour and which iterators survive an edit.
| Container | Layout | Access by index / key | Insert / erase | Iteration order |
|---|---|---|---|---|
vector<T> | One contiguous allocation, grows by reallocation | O(1) index | O(n) insert/erase in middle, amortised O(1) push_back | Storage order |
list<T> | Nodes linked by prev/next pointers | O(n) walk, no operator[] | O(1) given an iterator | Insertion order |
map<K,V> | Balanced tree nodes | O(log n) key lookup | O(log n) | Sorted by key |
unordered_map<K,V> | Buckets of nodes, hash of key picks bucket | Average O(1), worst O(n) | Average O(1) | Unspecified, changes on rehash |
vector vs list
vector wins when you read by index, iterate the whole range, or hand the buffer to C code. Iteration is sequential in memory, so a scan of 1 million int values touches one allocation. list pays two pointers per node plus allocation overhead, and a scan chases pointers across the heap. On a MediaTek embedded target with tight RAM, that overhead and fragmentation matter more than the asymptotic insert cost.
list wins for one case: frequent insert or erase in the middle when you already hold an iterator to that spot. vector shifts every following element. Erasing the second element of a 1 million element vector moves 999,998 elements. list unlinks one node.
// C++17. Compiled with -std=c++17.
#include <list>
#include <vector>
void bad() {
std::vector<int> v{1, 2, 3, 4};
auto it = v.begin() + 1; // points at 2
v.push_back(5); // may reallocate: it now dangles
*it = 99; // undefined behaviour if reallocation happened
}
void good() {
std::vector<int> v;
v.reserve(1024); // one allocation, no reallocation during fill
v.push_back(1);
auto it = v.begin();
v.push_back(2); // no reallocation, it stays valid
*it = 99;
std::list<int> l{1, 2, 3};
auto lit = std::next(l.begin());
l.push_back(4); // lit still points at 2, no reserve needed
l.erase(lit); // only lit is invalidated
}Iterator invalidation, worked trace
| Operation | vector | list | map / unordered_map |
|---|---|---|---|
| Insert, no reallocation | Iterators at or after insertion point invalidated | None invalidated | None invalidated |
| Insert causing growth / rehash | All iterators, references and pointers invalidated | None invalidated | vector: all. unordered_map rehash: all iterators invalidated, references and pointers to elements stay valid |
| Erase one element | Iterators at or after erased element invalidated | Only erased element invalidated | Only erased element invalidated |
clear() | All invalidated | All invalidated | All invalidated |
The practical bug pattern is holding a vector iterator or reference across a push_back in a loop, or holding an unordered_map iterator across an insert that triggers a rehash. The fix is to reserve or reserve equivalent capacity up front, re-acquire the iterator after the mutating call, or switch to a node based container when stability is the requirement.
map vs unordered_map
map keeps keys sorted, so range queries are natural: lower_bound, iterating keys in order, finding the predecessor. Cost is O(log n) per operation and a pointer chase per tree step. unordered_map trades order for average constant time. Its worst case is every key landing in one bucket, which turns lookup into a linear scan. That is not theoretical if keys are attacker controlled and the hash is predictable, so for untrusted input prefer a tree or a keyed hash with a random seed.
Two details interviewers probe. First, unordered_map iteration order is bucket order, and a rehash can change it without any key changing. Code that depends on order breaks silently. Second, unordered_map needs a good std::hash for the key type. The default hash for strings is fine, but a custom struct without a hash specialization will not compile, and a weak hash (for example, hashing only the first field of a composite key) recreates the worst case above.
When I would pick each
Default to vector for sequences. Default to unordered_map for key lookup when order does not matter and keys are trusted, and call reserve or max_load_factor to control rehash pauses. Pick map when sorted iteration or range queries are part of the contract. Pick list only when stable iterators across middle inserts are the actual requirement, and accept the memory and cache cost. In firmware code I would also ask whether a fixed size array or a ring buffer removes the allocation entirely, since none of these four containers guarantees a bounded allocation time.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7When does iterator invalidation occur, and how do you handle it?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
Iterator invalidation means a stored iterator, reference, or pointer no longer denotes a valid element because the container changed underneath it. What invalidates depends on the container and the operation, not on iterators in general. In vector and string, growth that reallocates invalidates everything. In list and map, erasing one element invalidates only that element. In unordered_map, rehashing invalidates iterators but leaves references and pointers to elements valid. The safe pattern is to never hold an iterator across a mutation unless you know that mutation cannot invalidate it, and to use the iterator returned by erase or insert when you must continue iterating.
| Container | Operation | Invalidated |
|---|---|---|
vector, string | push_back / emplace_back that reallocates | All iterators, references, pointers |
vector, string | push_back without reallocation | Only iterators past the end (the old end()) |
vector, string | insert / erase in the middle | Iterators at or after the point of change; reallocation invalidates all |
deque | push_front / push_back | Iterators, but not references or pointers |
deque | insert / erase in the middle | All iterators, references, pointers |
list | insert, erase, push_* | Only the erased element |
map, set | insert, erase | Only the erased element |
unordered_map, unordered_set | Rehash (growth) | All iterators; references and pointers stay valid |
unordered_map, unordered_set | insert / erase without rehash | Only the erased element |
That table is the whole interview answer in practice. The classic bug is erasing from a vector while iterating forward:
// C++17. Bug: erase shifts elements left, ++it skips the next one,
// and any reallocation during the loop would dangle it entirely.
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it % 2 == 0) v.erase(it);
}
// Fix: erase returns the iterator following the last removed element (C++11).
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0) it = v.erase(it);
else ++it;
}For map and unordered_map the same idiom works, and it is the only portable way to filter a container in place. Note the asymmetry for unordered_map: after a rehash, an iterator you saved may point nowhere even though the element still exists and a reference to it is still fine. Code that caches auto it = m.find(k) across insertions is therefore broken in a way that code caching const Value& ref = m[k] is not.
Handling it by design, not by luck
Four moves cover most production code I have seen in embedded and platform C++ at MediaTek scale, where a reallocation in a hot path also costs a copy of every element:
- Reserve up front. If you know the final size,
v.reserve(n)before filling removes reallocation invalidation entirely. It also removes the repeated copying that causes it. - Pick the container for the mutation pattern. Frequent erasure from the middle of a sequence is what
listormapexist for. Paying O(n) shifting in avectorto keep iterators simple is usually the wrong trade. Conversely, if you need random access and cache locality, do not switch tolistjust to dodge invalidation. - Do not store iterators as state. Store a key, an index, or a stable handle (an id, or a pointer into a node based container) and look the element up again. Long lived iterators into a container that other threads or callbacks mutate are a latent use after free. In firmware code this shows up as an iterator held across a callback that appends to the same container.
- Let the debug build catch it. Compile with
-D_GLIBCXX_DEBUG(libstdc++) or_ITERATOR_DEBUG_LEVEL=2(MSVC) during development. Both turn invalidation into an assertion instead of undefined behaviour that only reproduces under a particular allocation pattern. AddressSanitizer will not reliably catch a stale iterator into a still allocated buffer, so the checked iterators matter.
Failure mode to name in the interview
The dangerous case is not a crash. It is a stale iterator that still points inside the reallocated buffer, so the program reads freed or reused memory and produces wrong results intermittently. That is why "it worked in testing" proves nothing here. Allocation size, allocator behaviour, and reserve history decide whether reallocation happens, so the bug can vanish when a test input grows by one element. If an interviewer pushes, the answer is: state the container, state the operation, state what is invalidated, then show the it = erase(it) pattern or the reserve that removes the hazard.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Implement a deque from scratch.
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
I would implement it as a circular buffer over a dynamically grown array, not as a linked list. That gives O(1) amortised push and pop at both ends, O(1) access by index, and one contiguous allocation to copy on growth. A linked list also gives O(1) ends but loses indexing, hurts cache locality, and pays a node allocation per element. In C++ I would write it as a template, throw on pop from empty, and state up front that it is not thread-safe. If the interviewer wants concurrent use, I add a mutex or switch to a single-producer single-consumer ring, depending on the access pattern.
// C++17, checked against g++ 13
#include <cstddef>
#include <stdexcept>
#include <utility>
#include <vector>
template <typename T>
class Deque {
public:
Deque() = default;
void push_back(const T& v) {
if (size_ == buf_.size()) grow();
buf_[(head_ + size_) % buf_.size()] = v;
++size_;
}
void push_front(const T& v) {
if (size_ == buf_.size()) grow();
head_ = (head_ + buf_.size() - 1) % buf_.size();
buf_[head_] = v;
++size_;
}
T pop_back() {
if (size_ == 0) throw std::out_of_range("pop_back on empty deque");
T v = buf_[(head_ + size_ - 1) % buf_.size()];
--size_;
return v;
}
T pop_front() {
if (size_ == 0) throw std::out_of_range("pop_front on empty deque");
T v = buf_[head_];
head_ = (head_ + 1) % buf_.size();
--size_;
return v;
}
T& at(std::size_t i) {
if (i >= size_) throw std::out_of_range("deque index out of range");
return buf_[(head_ + i) % buf_.size()];
}
std::size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
private:
void grow() {
std::size_t new_cap = buf_.empty() ? 8 : buf_.size() * 2;
std::vector<T> next(new_cap);
for (std::size_t i = 0; i < size_; ++i)
next[i] = buf_[(head_ + i) % buf_.size()];
buf_ = std::move(next);
head_ = 0;
}
std::vector<T> buf_;
std::size_t head_ = 0;
std::size_t size_ = 0;
};The invariants are small enough to test directly: buf_.size() is capacity, head_ is the index of element 0, and element i lives at (head_ + i) % capacity. Growth copies in logical order and resets head_ to 0, which unwraps the ring.
Worked trace
The first grow() on an empty buffer sets capacity to 8, so the trace below uses capacity 8 throughout.
| Operation | Buffer (physical) | head_ | Logical order |
|---|---|---|---|
| push_back 1, 2, 3 | [1, 2, 3, _, _, _, _, _] | 0 | 1, 2, 3 |
| push_front 0 | [1, 2, 3, _, _, _, _, 0] | 7 | 0, 1, 2, 3 |
| pop_front returns 0 | [1, 2, 3, _, _, _, _, 0] | 0 | 1, 2, 3 |
| push_back 4, 5, 6, 7, 8 | [1, 2, 3, 4, 5, 6, 7, 8] | 0 | 1, 2, 3, 4, 5, 6, 7, 8 |
| push_back 9, grows to 16 | [1, 2, 3, 4, 5, 6, 7, 8, 9, _, _, _, _, _, _, _] | 0 | 1, 2, 3, 4, 5, 6, 7, 8, 9 |
Wrap only matters when head_ is not 0. After the growth above, pop_front twice, so head_ becomes 2 and the logical order starts at 3. Then push_back 10 through 17. The tail fills indices 9 to 15, then wraps to index 0. At that point at(0) still returns 3, because the modulo in at follows head_, and at(size() - 1) returns 17.
Why not the other designs
| Design | Ends | Indexing | Growth cost | Weak point |
|---|---|---|---|---|
| Circular array, this code | O(1) amortised | O(1) | O(n) copy, doubling | Copy pause on growth |
| Doubly linked list | O(1) | O(n) | O(1) per node | Node per element, poor locality |
| Chunked blocks, like std::deque | O(1) | O(1) via block map | O(1), no full copy | Two-level indirection, more code |
Doubling keeps the amortised cost at O(1) per push. With capacities 8, 16, 32 and so on, the total number of element copies made while growing to hold n elements is bounded by roughly 2n, so the average copy work per push stays constant even though any single growth costs O(n). Shrinking is the mirror problem. Shrinking at half full causes grow and shrink to thrash when the size hovers at the boundary, so I shrink at quarter full and halve capacity, or I skip shrinking entirely in firmware where a copy pause is worse than wasted RAM.
Failure modes I would name in the loop
Pop or at on an empty or out-of-range deque throws std::out_of_range instead of reading stale slots. That matters in embedded code where a stale read looks like valid sensor data. The second failure is exception safety during grow: if copying a T throws, buf_ still holds the old data because next is discarded, so the deque stays valid. The third is concurrency. Two threads pushing at once race on head_ and size_, which is undefined behaviour in C++ and can corrupt the structure in ways that are hard to reproduce, such as lost or duplicated elements or a size that disagrees with the contents. For a producer-consumer queue I would either guard this class with a mutex and condition variable, or replace it with a fixed-capacity SPSC ring that reports full explicitly. I would not silently drop or overwrite, since the caller needs to decide whether to block, drop, or raise an error.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9What is the difference between threads and processes, and what causes deadlocks?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
A process is a program in execution with its own virtual address space, page tables, file descriptor table and signal mask. A thread is a schedulable unit of execution inside a process. Threads in the same process share the address space, heap, globals and open files, but each has its own stack, registers, program counter and thread-local storage.
That sharing is the whole trade-off. Threads are cheap to create and communicate through shared memory, but a fault in one can corrupt data for all of them and the process dies. Processes isolate faults and enforce memory protection, but communication needs IPC such as pipes, sockets, shared memory with explicit synchronisation, or binder on Android, and a context switch between processes costs more because the kernel must switch address spaces and flush TLB entries.
On Linux, which is what most MediaTek Android and embedded Linux work runs on, both are scheduled by the kernel. clone() with CLONE_VM creates a thread, without it creates a process. A thread context switch inside one process is typically a few microseconds. A process switch is often 2 to 5 times that, and it grows if the working set no longer fits in cache. Those are order-of-magnitude figures on a Cortex-A78 class core, not guarantees.
| Process | Thread | |
|---|---|---|
| Address space | Private, protected by page tables | Shared with sibling threads |
| Stack and registers | Own | Own, per thread |
| Creation cost | Higher, page tables and kernel structures copied or created | Lower, mostly a new stack and task struct |
| Communication | IPC, signals, shared memory | Direct shared memory, needs locks |
| Fault isolation | Crash stays contained | Segfault or heap corruption kills the process |
| Scheduling | Kernel schedules tasks, threads are the schedulable entity | Same scheduler, finer granularity |
Deadlock
Deadlock is a cycle of threads each holding a resource the next one needs, so none can progress. The classic case is two mutexes taken in opposite order:
#include <pthread.h>
pthread_mutex_t a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;
void *thread1(void *arg) {
pthread_mutex_lock(&a);
pthread_mutex_lock(&b); /* waits if thread2 holds b */
pthread_mutex_unlock(&b);
pthread_mutex_unlock(&a);
return NULL;
}
void *thread2(void *arg) {
pthread_mutex_lock(&b);
pthread_mutex_lock(&a); /* waits if thread1 holds a */
pthread_mutex_unlock(&a);
pthread_mutex_unlock(&b);
return NULL;
}Worked trace:
| Step | Thread 1 | Thread 2 | State |
|---|---|---|---|
| 1 | locks a | holds a | |
| 2 | locks b | holds a, b | |
| 3 | tries b, blocks | thread 1 waiting | |
| 4 | tries a, blocks | both blocked, cycle formed |
The four Coffman conditions describe when this can happen: mutual exclusion, hold and wait, no preemption, and circular wait. Break any one and deadlock becomes impossible. In practice we break circular wait with a global lock ordering. If every thread takes a before b, thread 2 in the example would block on a at step 2 instead of taking b, and thread 1 finishes.
Prevention is preferred over recovery. Lock ordering and keeping critical sections short are the first line. Where ordering is hard, for example with a driver callback and a HAL lock, use pthread_mutex_trylock() with a bounded retry and backoff, or a timed lock, and log the contention so it shows up in traces. Detection exists on Linux through lockdep in debug kernels and through watchdog timeouts in RTOS builds, but in production you usually detect it indirectly: a thread that never returns from a lock call, a watchdog firing, or an ANR on Android when the main thread is stuck.
Two failure modes worth naming in an interview. Priority inversion: a low priority thread holds a lock a high priority thread needs, while a medium priority thread preempts the low one, so the high priority thread waits indefinitely. Priority inheritance on the mutex fixes that on Linux and in most RTOS kernels. The second is lock ordering across layers, common in MediaTek modem and connectivity stacks where a framework lock and a driver lock meet. Document the order in the header that declares both locks, because the next engineer will not guess it from the code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Implement an LRU cache.
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
I would implement it with a hash map from key to node, plus a doubly linked list ordered by recency. The map gives O(1) lookup. The list gives O(1) move-to-front on a hit and O(1) eviction from the tail. That combination is what makes both get and put O(1) average time, which is the point of the question.
Assumptions I would state first: capacity is fixed and at least 1, keys and values are copyable, and the caller handles thread safety unless we add a lock. In C++ I would use std::list for the list and std::unordered_map for the index, storing an iterator to the list node in the map so I never search the list.
// C++17
#include <list>
#include <unordered_map>
#include <optional>
#include <utility>
template <typename K, typename V>
class LRUCache {
public:
explicit LRUCache(std::size_t capacity) : capacity_(capacity) {}
std::optional<V> get(const K& key) {
auto it = index_.find(key);
if (it == index_.end()) return std::nullopt;
order_.splice(order_.begin(), order_, it->second); // move to front
return it->second->second;
}
void put(K key, V value) {
auto it = index_.find(key);
if (it != index_.end()) {
it->second->second = std::move(value);
order_.splice(order_.begin(), order_, it->second);
return;
}
if (index_.size() == capacity_) { // evict least recently used (back)
auto lru = std::prev(order_.end());
index_.erase(lru->first);
order_.erase(lru);
}
order_.emplace_front(std::move(key), std::move(value));
index_[order_.front().first] = order_.begin();
}
private:
std::size_t capacity_;
std::list<std::pair<K, V>> order_; // front = most recent
std::unordered_map<K, std::list<std::pair<K, V>>::iterator> index_;
};std::list::splice moves a node without copying the pair and without invalidating iterators, so the iterator stored in the map stays valid after a move. That detail matters. If I erased and reinserted instead, I would pay a copy and risk breaking the stored iterator.
Worked trace, capacity 3
| Step | Operation | List front to back | Effect |
|---|---|---|---|
| 1 | put(1, a) | 1:a | insert |
| 2 | put(2, b) | 2:b, 1:a | insert |
| 3 | put(3, c) | 3:c, 2:b, 1:a | insert, now full |
| 4 | get(1) | 1:a, 3:c, 2:b | hit, 1 moves to front |
| 5 | put(4, d) | 4:d, 1:a, 3:c | evict 2, the tail |
| 6 | get(2) | 4:d, 1:a, 3:c | miss, list unchanged |
| 7 | put(3, C) | 3:C, 4:d, 1:a | update in place, no eviction |
Step 7 is the case candidates miss. Updating an existing key must refresh recency and must not trigger eviction, even though the size does not grow.
Trade-offs and failure modes
| Design | Get/Put | Memory overhead | When I would pick it |
|---|---|---|---|
Hash map + std::list | O(1) average | One node per entry plus hash bucket array | General purpose, as above |
| Hash map + intrusive list | O(1) average | Lower, no separate node allocation | Embedded or hot path where allocation cost matters |
| Array + linear scan | O(n) | Minimal | Tiny fixed cache, say under 16 entries, where simplicity wins |
Three failure modes I would name before the interviewer asks. First, unordered_map degrades to O(n) under hash collisions or a poor hash for the key type, and rehashing can spike latency. I would reserve buckets up front when the capacity is known, for example index_.reserve(capacity_ * 2). Second, capacity 0 makes the eviction branch erase from an empty list. I would reject it in the constructor or handle it explicitly rather than let it crash. Third, the class as written is not thread safe. Two threads calling get concurrently can splice the same node twice. For a shared cache I would guard both methods with a mutex, or use a sharded design if contention shows up in profiling.
For a MediaTek style constraint, where the cache might sit in firmware with a tight memory budget, I would also flag that std::list allocates per node and unordered_map bucket overhead can exceed the payload for small values. An intrusive doubly linked list embedded in a fixed pool of slots removes per node allocation and makes the memory cost predictable: capacity * (key + value + two pointers). I would only go there if profiling or the memory budget forced it, since the standard version is easier to review and harder to corrupt.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Walk me through your master's thesis and coursework.
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
"My master's was in embedded systems, 2022 to 2024. My thesis was power-aware scheduling on a heterogeneous SoC. I had to place a vision pipeline, either on a Cortex-A78 or on a small accelerator, and hold a 33 ms frame deadline while cutting energy. I wrote the scheduler in C, ran it on an ARM board, and measured latency from frame-ready interrupt to output write. At the same model accuracy, my scheduler held p99 at 31 ms and cut energy per frame by 18 percent against fixed placement on the accelerator."
I stop there. That gives the interviewer a problem, a platform, and a number to challenge. A staff interviewer will usually challenge the placement policy next, so I am ready for that trade-off before they ask.
Coursework I actually used
I name four courses and what each one changed.
| Course | What it changed in the thesis |
|---|---|
| Operating Systems | Locking around the shared frame buffer, and how I avoided priority inversion when the accelerator driver held a lock |
| Computer Architecture | Cache and bandwidth estimates, which decided what data stayed on chip |
| Real-Time Systems | Deadline budgeting and worst-case testing under thermal throttling |
| Digital Signal Processing | Fixed-point quantisation before the accelerator, which changed the energy cost per frame |
The placement trade-off
Three policies were credible for this hardware. I implemented the middle one and benchmarked the other two, because the choice only makes sense against them.
| Policy | Latency behaviour | Energy | Weakness |
|---|---|---|---|
| Fixed on accelerator | Lowest average latency, about 19 ms p50 in my runs | Lowest when the accelerator stays busy | p99 blew past 33 ms when the queue backed up or the part throttled |
| Fixed on A78 | Predictable, p99 about 29 ms | About 40 percent higher per frame | Wasted the accelerator and left no headroom for a larger model |
| Dynamic, mine | p50 about 24 ms, p99 31 ms | 18 percent below fixed accelerator at equal accuracy | Paid a migration cost when it switched cores mid-stream |
The criteria were deadline first, energy second, migration cost third. That ordering matters. A policy that saves energy but misses the deadline fails the product requirement, so energy only counted once p99 stayed under 33 ms. Migration cost came last because a switch cost about 0.8 ms to flush and refill the pipeline buffers, which I could absorb if it happened rarely.
The decision logic was deliberately small:
/* Checked per frame, using the previous frame's measurements. */
if (accel_queue_ms > 12 || accel_busy_ms > 20) {
place_on_cpu();
} else if (cpu_queue_ms > 18 && temp_c < 82) {
place_on_accel();
} else {
keep_current_core();
}Keeping the current core unless a threshold was crossed was the key judgement. Without that hysteresis, the scheduler oscillated between cores and paid the 0.8 ms migration cost every few frames. With it, switches dropped from roughly 1 in 4 frames to 1 in 40.
A worked trace
One run, 10,000 frames, accelerator queue building during a thermal event:
| Frame range | Accelerator queue | Policy action | p99 in window |
|---|---|---|---|
| 1 to 2,000 | 4 to 8 ms | Stay on accelerator | 26 ms |
| 2,001 to 2,400 | 14 to 22 ms | Move to A78 | 31 ms |
| 2,401 to 3,000 | Falls below 6 ms | Move back after 50 stable frames | 28 ms |
The 50-frame hold before moving back stopped the flapping I had seen in the first prototype.
Failure modes I would expect to be pressed on
Two came up in testing. First, DVFS made cycle counts incomparable between runs, so I normalised by current frequency and logged frequency with every sample. Second, the accelerator driver could block the enqueue path for over 2 ms. I added a bounded wait and fell back to the A78 core when it expired.
If asked what I would do differently, I would add hardware tracing in week one. I spent about three weeks inferring queue behaviour from logs that a trace would have shown in days. That is the habit I would bring to a product team. Instrument first, then tune the policy."
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12How do CPU pipelines work, and what hazards do they introduce?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
A pipeline overlaps the stages of successive instructions instead of finishing one instruction before starting the next. In a classic 5-stage RISC pipeline the stages are fetch, decode, execute, memory, and writeback. While instruction 2 is in decode, instruction 1 is in execute, and so on. Once the pipe is full, throughput approaches one instruction per cycle, even though each instruction still takes five cycles from fetch to writeback. Latency and throughput are different numbers, and interviewers care that you keep them separate.
The overlap is where hazards come from. A hazard is any condition where the next instruction cannot proceed in the next cycle without producing a wrong result or wasting work. The standard split is structural, data, and control hazards, and each has a different fix.
Forwarding in that diagram is a bypass from the execute/memory pipeline register (and, for a load, from the memory stage output) directly into the ALU input of the instruction currently in execute. It does not go through writeback or the register file, which is why it can supply a result one or two cycles earlier than a register read would.
Data hazards: the common case
The most frequent one is read-after-write. Consider:
// C, checked against GCC 13 for ARM64 (-O2)
int x = a + b;
int y = x * c; // needs x from the previous lineWhen y = x * c reaches execute, the add may still be in memory or writeback, so x is not ready. Without handling, the core reads a stale register. Three mechanisms close the gap. Forwarding (bypassing) sends the ALU result directly from the end of execute to the next instruction's input, which removes most stalls. Register renaming in an out-of-order core removes false dependencies (write-after-read and write-after-write) by giving each write a fresh physical register. Load-use is the stubborn case: a load result is only available after memory, so even with forwarding the dependent instruction typically stalls for one or more cycles. A compiler can hide that stall by moving an independent instruction between the load and its use, which is instruction scheduling.
| Hazard | Example | Typical cost | Main mitigation |
|---|---|---|---|
| Structural | Single memory port needed by fetch and load in the same cycle | Fetch bubble, 1 cycle or more | Separate instruction and data caches, dual ports |
| Data: read-after-write | y = x * c after x = a + b | 0 cycles with forwarding, 1+ for load-use | Forwarding, renaming, scheduling |
| Data: write-after-read | Later write overwrites a register still being read | Wrong value if executed in order | Renaming in out-of-order cores |
| Control | Branch target unknown until execute | Flush of younger instructions | Branch prediction, delayed slots (older designs) |
Control hazards and the arithmetic
A branch creates a control hazard because fetch does not know the next address until the branch resolves. The classic fix is prediction: a branch predictor guesses taken or not taken, fetch continues on the guess, and a misprediction flushes the wrong-path instructions. That flush is the cost. With a hypothetical 15-cycle misprediction penalty and a 5% misprediction rate on branches that are 20% of instructions, the CPI contribution is 0.20 x 0.05 x 15 = 0.15 extra cycles per instruction. On a core targeting CPI of 0.5, that is a 30% slowdown from branches alone, which is why predictor accuracy matters more than raw clock speed in branch-heavy code such as parsers and interpreters.
A worked trace makes the flush concrete. Cycles are hypothetical, for a 5-stage in-order core where the branch resolves at the end of execute in cycle 3:
| Cycle | Fetch | Decode | Execute | Memory | Writeback |
|---|---|---|---|---|---|
| 1 | branch | ||||
| 2 | wrong path 1 | branch | |||
| 3 | wrong path 2 | wrong path 1 | branch (resolves) | ||
| 4 | correct target | bubble | bubble | branch | |
| 5 | target + 1 | correct target | bubble | bubble | branch |
| 6 | target + 2 | target + 1 | correct target | bubble | bubble |
The branch advances one stage per cycle, from fetch in cycle 1 to writeback in cycle 5. The two wrong-path instructions fetched in cycles 2 and 3 are flushed before they reach execute, and the correct target enters fetch in cycle 4. Deeper pipelines, such as the 14-plus stage designs in high-frequency out-of-order cores, pay a larger penalty per flush, which is one reason MediaTek's efficiency cores and performance cores make different trade-offs.
Why this matters on a MediaTek SoC
In-order cores like Cortex-A53 keep the pipeline short and simple, so a flush is cheap and power stays low, at the cost of stalling on every load-use and cache miss. Out-of-order cores like Cortex-A78 add renaming, a reorder buffer, and a large predictor to keep the pipe full, but a misprediction now discards more speculative work and burns more energy. That energy cost is not abstract on a phone SoC: a flush during a sustained workload raises power in a thermal envelope that is already tight. When I profile firmware or a driver and see high cycles per instruction with a high branch-miss counter in the performance monitor, my first check is whether the hot loop has an unpredictable branch or a load whose result feeds the next instruction, because those two patterns map directly onto the hazards above.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13What are the roles of the linker and compiler in building a program?
Reported in Mediatek Software Engineer Interview Guide
The 90-second answer
The compiler turns one source file into an object file for a target machine. The linker turns many object files, plus libraries, into one executable and fixes up every reference between them. Neither step alone produces a runnable program.
// main.c
extern int sensor_init(void);
int main(void) { return sensor_init(); }// sensor.c
int sensor_init(void) { return 0; }arm-none-eabi-gcc -c main.c -o main.o
arm-none-eabi-gcc -c sensor.c -o sensor.o
arm-none-eabi-gcc main.o sensor.o -o app.elfmain.o compiles cleanly even though sensor_init is not defined in main.c. The compiler records it as an undefined symbol. Only the linker, seeing both objects, can resolve it.
What the compiler does
Preprocessing, parsing, semantic analysis, optimisation, and code generation happen per translation unit. The output is machine code in relocatable sections, usually ELF .o, with a symbol table and relocation entries where addresses are not yet known. For example, a call to sensor_init is emitted with a placeholder address and a relocation record saying "patch this offset once the target address is known."
The compiler also decides calling convention, register allocation, inlining, and which sections a symbol lands in. With -ffunction-sections -fdata-sections, each function gets its own section, which matters later for dead code removal.
What the linker does
The linker has three jobs: symbol resolution, relocation, and layout.
| Job | What happens | Example failure |
|---|---|---|
| Symbol resolution | Matches undefined symbols to definitions across objects and archives | undefined reference to 'sensor_init' |
| Relocation | Patches placeholders with final addresses and offsets | relocation truncated to fit on a small embedded target |
| Layout | Places sections into memory regions in order, honours alignment and a linker script | section .text will not fit in region FLASH |
It also pulls members out of static archives (.a) only when they resolve an undefined symbol, which is why link order can matter with GNU ld. With shared libraries (.so), it records dynamic dependencies instead of copying the code, and the dynamic loader finishes relocation at load time.
Why this split matters at MediaTek
Firmware for a chipset rarely uses a host compiler. A cross compiler such as arm-none-eabi-gcc targets the Cortex core, its ABI, and its instruction set. The linker script then maps sections to physical memory: startup code and .text in flash, initialised .data copied from flash to SRAM at boot, and .bss zeroed in SRAM. The compiler knows nothing about that memory map. The linker script and the linker enforce it.
Static linking is common in firmware because there is no dynamic loader to resolve a .so at runtime. That makes the binary self-contained but larger, so teams use --gc-sections to discard unused function sections, strip symbols with arm-none-eabi-strip, and check size with size app.elf. A 40 KB overrun in .text is caught at link time, not when the device boots.
Failure modes I would name in the loop
Undefined reference usually means a missing object, a missing library, or wrong link order. Multiple definition usually means the same non-inline function compiled into two objects, or a header defining a global instead of declaring it extern. A truncated relocation on ARM often means code compiled for a 32-bit address space linked into a region beyond that range, or a mismatch between the compiler flags and the linker script. I would inspect them with nm app.o, readelf -s main.o, and arm-none-eabi-ld --print-map to see where each section landed and which archive member was pulled in.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Find the unique number in an array?
Reported in MediaTek Online Assessment Experience 2026 | Aptitude, Digital ...
The 90-second answer
I would first pin down the contract, because "unique" changes the algorithm. The classic version is: an array of integers where every value appears exactly twice except one value that appears once. For that version XOR is O(n) time and O(1) extra space.
XOR has the properties a ^ a = 0, a ^ 0 = a, and it is commutative and associative. Pairs cancel out, the single element survives.
// C++17
#include <vector>
int findUnique(const std::vector<int>& a) {
int result = 0;
for (int x : a) {
result ^= x;
}
return result;
}Trace for [4, 1, 2, 1, 2]:
| Step | x | result after result ^= x |
|---|---|---|
| 0 | - | 0 |
| 1 | 4 | 4 |
| 2 | 1 | 5 |
| 3 | 2 | 7 |
| 4 | 1 | 6 |
| 5 | 2 | 4 |
Result is 4, the only value seen once.
If the interviewer changes the numbers
The follow-ups usually change the repetition count or the ordering. I would name which variant I am solving before coding it.
| Variant | Approach | Cost |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| Every value twice, one once | XOR all elements | O(n) time, O(1) space |
| Every value k times (k > 2), one once | Count bits per position across all numbers, take mod k, rebuild | O(32n) time, O(1) space |
| Sorted array, one unique, rest in pairs | Binary search on pairs, or check neighbours | O(log n) or O(n) time |
| Unsorted, no space limit | Hash map of counts | O(n) time, O(n) space |
For the k-times case, XOR alone fails. Example: [6, 6, 6, 3] XORs to 3 ^ 6 ^ 6 ^ 6 = 3 ^ 6 = 5, which is wrong. Counting bits fixes it: for each of the 32 bit positions, sum how many numbers have that bit set, take the sum mod k, and set the bit in the answer if the remainder is non-zero. That also handles negative numbers if you work on the two's complement representation and use unsigned arithmetic internally.
Failure modes and edge cases
Empty array: there is no unique element, so I would either require non-empty input in the contract or throw std::invalid_argument. Returning 0 silently would be indistinguishable from a legitimate answer of 0.
Input that breaks the promise, such as three copies of the unique value or two singletons: XOR returns some value with no error. If the caller cannot guarantee the promise, I would validate with a hash map first and report the violation instead of returning a plausible-looking wrong answer.
Floating point values: XOR does not apply. I would fall back to sorting or a hash map, and for floats I would also worry about representation equality.
Overflow is not an issue for XOR itself since it operates bitwise, but signed overflow in the bit-counting variant is, which is why that version uses uint32_t or uint64_t for the bit manipulation.
In a MediaTek loop I would write the XOR version first, state its assumption out loud, then offer the bit-counting version for k repetitions. That shows the fast path and that I know where it stops working.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15How would you swap specific bits at given positions in an integer, and what edge cases would you check?
Reported in MediaTek Online Assessment Experience 2026 | Aptitude, Digital ...
The 90-second answer
I would first pin down what "swap" means, because interviewers use it for two different operations. The common one is swapping the single bits at positions i and j. The other is swapping two fields of n bits each. I will answer the single-bit version, then show the field version, since the mechanism is the same.
For a single bit, extract both bits, clear both positions, then write each bit into the other's place. The branchless form does that with one XOR:
#include <stdint.h>
uint32_t swap_bits(uint32_t x, unsigned i, unsigned j)
{
if (i >= 32 || j >= 32 || i == j)
return x; /* caller decides: reject or no-op */
uint32_t diff = ((x >> i) ^ (x >> j)) & 1u;
return x ^ (diff << i) ^ (diff << j);
}If the bits are equal, diff is 0 and the XORs change nothing. If they differ, diff is 1 and both positions flip, which is exactly a swap. No branch, no temporary per bit.
Worked trace
Take x = 0b10110010 (0xB2), swap positions 1 and 5. Positions are 0-based from the LSB.
| Step | Value |
|---|---|
| --- | --- |
| --- | --- |
| --- | --- |
| bit 1 of x | 1 |
| bit 5 of x | 1 |
diff | 0 |
| result | 0b10110010, unchanged |
That pair is a poor demo because both bits are 1. Swap positions 0 and 1 instead:
| Step | Value |
|---|---|
| --- | --- |
| bit 0 of x | 0 |
| bit 1 of x | 1 |
diff | 1 |
x ^ (1 << 0) ^ (1 << 1) | 0b10110011 (0xB3) |
Bit 0 is now 1 and bit 1 is now 0. The other six bits are untouched, which the XOR guarantees because only those two masks are applied.
Swapping fields
If the question means two n-bit fields starting at p and q, mask and shift each field, then clear and reinsert:
uint32_t swap_fields(uint32_t x, unsigned p, unsigned q, unsigned n)
{
uint32_t mask = (n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u);
uint32_t a = (x >> p) & mask;
uint32_t b = (x >> q) & mask;
x &= ~(mask << p);
x &= ~(mask << q);
return x | (a << q) | (b << p);
}This needs the extra checks that the single-bit version hides: p + n <= 32, q + n <= 32, and the fields must not overlap. Overlapping fields have no well-defined swap, so I would reject them rather than return a silently wrong value.
Failure modes I would name unprompted
| Pitfall | What breaks | Fix |
|---|---|---|
| --- | --- | --- |
1 << i with signed int | shifting into the sign bit at i = 31 is undefined behaviour | use 1u << i, or 1ULL for 64-bit |
i or j at or past the width | shift by 32 or more on a 32-bit value is undefined behaviour | validate range before shifting |
1u << n when n = 32 | shift by the full width again | special-case the mask, as above |
| swapping bits in a memory-mapped register | read-modify-write is not atomic, an interrupt or DMA can interleave | use the hardware's set/clear registers or a lock, not a plain read, modify, write |
The last one matters in firmware work. The arithmetic above is correct for a value in a register or a local variable. Pointed at a peripheral register it can corrupt a concurrent update, so I would say that distinction out loud.
Alternatives and when not to use this
The extract, clear, set version (x = (x & ~(1u<<i)) | (bj<<i); x = (x & ~(1u<<j)) | (bi<<j);) is easier to read in a code review and costs a few more instructions. I would use it in production code and keep the XOR trick for when the interviewer asks for branchless or minimal code. If the positions come from untrusted input, neither version is safe without the range check, and I would return an error code instead of the input unchanged, so the caller cannot mistake a rejected swap for a successful one.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16What is the value of sizeof(struct) for a given struct definition, and why?
Reported in MediaTek Online Assessment Experience 2026 | Aptitude, Digital ...
The 90-second answer
sizeof(struct) is not the sum of its members. The compiler inserts padding between members so each member sits at an address that is a multiple of its alignment, and it adds tail padding at the end so the struct's alignment is preserved when structs are placed in an array. The exact value depends on the compiler, target ABI and packing settings, so I would state those assumptions before giving a number.
Assume C compiled with GCC or Clang for x86-64 System V, where char has size and alignment 1, int has 4 and 4, and double has 8 and 8. Consider:
#include <stdio.h>
#include <stddef.h>
struct S {
char a;
int b;
char c;
double d;
char e;
};
int main(void) {
printf("sizeof(struct S) = %zu\n", sizeof(struct S));
printf("offsetof b = %zu\n", offsetof(struct S, b));
printf("offsetof d = %zu\n", offsetof(struct S, d));
}Output: sizeof(struct S) = 32, offsetof b = 4, offsetof d = 16.
Worked trace
| Member | Size | Alignment | Offset | Padding before it |
|---|---|---|---|---|
a | 1 | 1 | 0 | 0 |
b | 4 | 4 | 4 | 3 bytes at 1-3 |
c | 1 | 1 | 8 | 0 |
d | 8 | 8 | 16 | 7 bytes at 9-15 |
e | 1 | 1 | 24 | 0 |
| tail | - | 8 (struct alignment) | 25-31 | 7 bytes |
Members occupy 15 bytes. Padding adds 17, giving 32. The tail padding is the part candidates miss. Without it, sizeof would be 25, and an array of struct S would place the second element at offset 25, where its double member would sit at an address that is not a multiple of 8.
Reordering changes the answer
struct T {
double d;
int b;
char a;
char c;
char e;
};Here d is at 0, b at 8, the three char members at 12, 13 and 14, and one tail byte brings sizeof(struct T) to 16. Same members, half the size. That is why ordering members from largest alignment to smallest is a common optimisation in memory constrained firmware, which is relevant at MediaTek, and why I would check offsetof rather than guess.
Where candidates get caught
Packing pragmas change the rules. #pragma pack(1) or __attribute__((packed)) on struct S removes inter-member and tail padding, giving 15, but the compiler may then generate unaligned accesses for b and d. On x86 that often still runs, slowly. On many ARM cores it can fault or produce incorrect results depending on the core and compiler settings. Packed structs are also a portability trap for wire formats and file formats. sizeof tells you the in-memory layout under the current ABI, not a stable on-disk layout. For serialisation I would define the format explicitly and copy fields one by one.
Other traps: a pointer member is 8 bytes on x86-64 and 4 bytes on a 32-bit ARM target, so the same source gives different sizes across builds. Nested structs inherit the inner struct's size including its tail padding. Bit-fields have implementation defined allocation, so sizeof on a struct containing them is not portable to reason about by hand. An empty struct has size 1 in C as a GCC extension, and 1 in C++ by the standard, because distinct objects need distinct addresses.
If an interviewer gives a definition without a target, the safe answer is the method: list each member's size and alignment, place them in order, add padding to satisfy alignment, add tail padding to a multiple of the strictest alignment, and verify with sizeof and offsetof on the actual toolchain.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Walk me through your projects and the mobile communication and OS concepts behind them?
Reported in Mediatek Interview Process Insights | PDF - Scribd
The 90-second answer
I will use one project in depth and keep the rest to a sentence each. My final year project streamed vibration data from a motor over LTE-M to a server, and raised an alert when the RMS level stayed above a threshold for 10 seconds. The sensor board ran Linux, the modem handled the cellular link, and an Android app displayed the alert.
The decisions I can defend are the ones between those parts. The kernel driver had to hand samples to userspace without sleeping in interrupt context. The modem had to sleep to save battery without making the server think the node had died. The Android app had to show alerts without keeping the CPU awake all night. Those three constraints drove the design.
I can go layer by layer from the sensor interrupt to the server acknowledgement if that helps.
Architecture
The daemon reads samples in batches, computes RMS over a 1 second window, and opens a network connection only when the value is interesting or every 60 seconds as a heartbeat. Sending every sample would have kept the modem session awake continuously. Sending only alerts meant the server needed the heartbeat to distinguish "no alert" from "node is dead".
OS concepts in the driver and daemon
The driver used a single-producer, single-consumer ring buffer. The producer was the interrupt handler on one CPU. The consumer was the daemon thread. That assumption is the whole design. It does not generalise to multiple producers without a lock or a different queue.
// C11, checked with gcc 13 -std=c11 -Wall -Wextra
#include <stdatomic.h>
#include <stdint.h>
#define CAP 1024
typedef struct {
int16_t buf[CAP];
_Atomic unsigned head; /* written by producer only */
_Atomic unsigned tail; /* written by consumer only */
} ring_t;
static int ring_push(ring_t *r, int16_t v) {
unsigned head = atomic_load_explicit(&r->head, memory_order_relaxed);
unsigned tail = atomic_load_explicit(&r->tail, memory_order_acquire);
unsigned next = (head + 1) % CAP;
if (next == tail) return -1; /* full: drop and count it */
r->buf[head] = v;
atomic_store_explicit(&r->head, next, memory_order_release);
return 0;
}The release store on head publishes the sample write to the consumer. The acquire load on tail pairs with the consumer's release store when it frees a slot. Without that ordering, on ARM the consumer could see the new head before it sees the sample. The full case returns an error instead of overwriting, and the driver increments a dropped-sample counter reported in the heartbeat. Silent overwrite would have kept RMS values looking plausible while hiding an overloaded I2C bus at 800 Hz.
On Android, the app used WorkManager for periodic sync and a foreground service only while the detail screen was open. A background service alone was killed under memory pressure on the 4 GB test phone. FCM delivered the push, but the app still fetched alert state on open because a push is a hint, not a delivery guarantee.
Mobile communication concepts
| Concept | Decision in the project | Failure mode I hit |
|---|---|---|
| LTE-M PSM and T3412 | Modem registered, sent data, then entered Power Saving Mode | Server saw a gap and flagged the node offline |
| UDP vs TCP for telemetry | UDP for samples, TCP for alert acknowledgement | UDP loss during handover corrupted one RMS window |
| Cell handover and RSRP | Logged RSRP and RSRQ with each heartbeat | Alerts stopped in a basement site with RSRP below -120 dBm |
| Android Doze and exact alarms | Sync moved to WorkManager, 15 minute minimum interval | Inexact alarms batched until the user opened the app |
For PSM, the precise point is the timer, not the modem alone. In 3GPP TS 24.008, the extended T3412 value can reach 310 hours, but the network sets the actual value in the attach accept. In our test the carrier profile set T3412 to 1 hour, so the node was unreachable for most of that hour by design. Disabling PSM would have drained the battery in days. The fix was on the server. It treated silence as expected and alarmed only after two missed heartbeats.
For Android power, two separate mechanisms mattered and I initially conflated them. Doze, introduced in Android 6.0, defers inexact alarms and jobs during idle periods. Exact alarms are a different restriction. From Android 12 (API 31) an app needs SCHEDULE_EXACT_ALARM permission to set them, and from Android 14 (API 34) that permission is denied by default for most apps. My test device ran Android 13 and did not hold the permission, so the exact alarm I used for the demo did not fire on schedule. Moving the sync to WorkManager with a 15 minute minimum interval made the behaviour explicit and testable.
Other projects, briefly
A coursework project simulated TCP congestion control in Python, which showed slow start and AIMD as behaviour over time rather than formulas. A hackathon project was a BLE beacon app, which taught me the difference between advertising interval and connection interval, and why a 100 ms advertising interval costs battery even with no connection.
If you push on any layer, the modem state machine and the ring buffer are where I have the most depth, including the bugs I introduced and how I found them with a logic analyser on the I2C line and packet captures on the modem UART.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: