Skip to main content
All Questions

Refactor and speed up a slow but correct C++ function.

Unlock detailed company stats for this questionUpgrade

The task as given (the current implementation is correct but slow):

// Refactor and speed up the code below // The current implementation is correct but slow

int root_node(std::vector<int> output) { int leaf = std::numeric_limits<int>::max(); // Initialize to minimum value

int x = 0, counter = 1; for (size_t node = 0; node < output.size(); ++node) { int edge = output[node]; auto begin = output.begin(); std::advance(begin, node); auto it = std::find_if(begin, output.end(), [edge](int node) { return edge == node; }); x = std::abs(edge); for (size_t j=0, j!= Std::end(output) && j<output.size()-node ,++j)

{ int vertex =output[(j+node)%output.size()];

constexpr auto digits = std::numeric_limits<int>::digits; int direction = ((unsigned int)(vertex - edge)) >> digits; int distance = (1 - direction) * std::pow(edge - vertex, 2); if (leaf == std::numeric_limits<int>::max()) { leaf = std::min(leaf, distance); } else if (distance == std::numeric_limits<int>::max()) { leaf = std::min(leaf, distance); } else { leaf = std::max(leaf, distance); // should this be min? } } } int j = [&](int old_value) { if (counter > x) { leaf = std::min(leaf, old_value); return old_value; } return leaf; }(leaf); for (int ff = 0; ff < leaf; ++ff) { if (ff * ff == leaf) { return ff; } } return leaf;

}

Format · Online assessment.

Community answers

No answers contributed by the community yet.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.