Can a Fibonacci function be written to execute in O(1) time?

Here is a near O(1) solution for a Fibonacci sequence term. Admittedly, O(log n) depending on the system Math.pow() implementation, but it is Fibonacci w/o a visible loop, if your interviewer is looking for that. The ceil() was due to rounding precision on larger values returning .9 repeating. Example in JS: function fib (n) { … Read more

What is the cost/ complexity of insert in list at some location?

list The Average Case assumes parameters generated uniformly at random. Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move). If you need to add/remove at both … Read more

Move all odd positioned element to left half and even positioned to right half in-place

Get largest sub-array having size 3k+1 Apply cycle leader algorithm to the parts of this sub-array, starting from positions 1, 3, 9, … 3k-1: move element to its proper position in sub-array (even-indexed elements to the left of sub-array, odd-indexed – to the right), the replaced element should be also moved to its proper position, … Read more

Finding the most frequent character in a string

There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later): import collections s = “helloworld” print(collections.Counter(s).most_common(1)[0]) If you don’t have that, you can do the tally manually (2.5 or later has defaultdict): d = collections.defaultdict(int) for c in s: d[c] += 1 print(sorted(d.items(), key=lambda … Read more

Java Math.pow(a,b) time complexity

@Blindy talks about possible approaches that Java could take in implementing pow. First of all, the general case cannot be repeated multiplication. It won’t work for the general case where the exponent is not an integer. (The signature for pow is Math.pow(double, double)!) In the OpenJDK 8 codebase, the native code implementation for pow can … Read more

What is the time complexity of Python list’s count() function?

Dig into the CPython source code and visit Objects/listobject.c, you will find the source code for the count() method in there. It looks like this: static PyObject * list_count(PyListObject *self, PyObject *value) { Py_ssize_t count = 0; Py_ssize_t i; for (i = 0; i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ); if … Read more