Full / Empty Buffer distinction in Circular Queue - arrays

In array implementation of circular queue if we point front to a slot before the first element and rear to the last element, hen we face the problem of how to identify whether the queue is full or empty.
To solve this problem we use either a counter or waste one space in the buffer.
I was thinking of the following approach. Please correct me where I am going wrong, and if not please let me know if this is a better/worse solution than the above.
Point front to the first element and rear to the last element;
Have a function to check if the Queue has only 1 element left;
If we are dequeing the last element, make front and rear -1;
isEmpty() will be true if both front & rear are -1;
isFull will be true if front = (rear + 1) % size.

There is not much wrong logically with this approach. You are treating negative values in front and rear as a kind of flag to indicate the queue is empty. Assuming your logic to update front and rear keeps the values in the range 0..size, you only need to set one of them to be outside that range to indicate the queue is empty.
Consider this alternative. Many circular queues work with the front and rear indices as unsigned values, and the size as a power of 2. The updating of their values is always to increment, and they are allowed to wrap around. This avoids complicated logic to adjust those indices. Because the indices are unsigned, even if they wrap around, the difference arithmetic works properly to determine the number of elements.
The trick with the modulus working even if the indices wrap around on increment is that size is a power of 2. This ensures that the wrapping around does not affect the modulus computation.
unsigned front_ = 0, rear_ = 0;
Type q_[SIZE];
unsigned getCount () { return rear_ - front_; }
bool isEmpty () { return getCount() == 0; }
bool isFull () { return getCount() == SIZE; }
bool enQ (Type val) {
bool result = !isFull();
if (result) q_[rear_++ % SIZE] = val;
return result;
}
bool deQ (Type *val) {
bool result = !isEmpty();
if (result) *val = q_[front_++ % SIZE];
return result;
}

Related

Find the index of the farthest smaller number in the right side of an array

Given an array of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1
This question is taken from here
Sample Test Cases
Input
3, 1, 5, 2, 4
Output
3, -1, 4, -1, -1
Input
1, 2, 3, 4, 0
Output
4, 4, 4, 4, -1
I would also like to clarify that this is not a duplicate of this post here. While I did understand the solution mentioned in the post, I would really like to know why the above approach does not work for all test cases.
I came up with the following approach,
Create a binary search tree from the right side of the array
Each node stores the following info - the value, the index of the current element and the index of the smallest element which is farthest away from it's right side
While inserting, check if the current element being inserted (while moving to the right subtree) satisfies the condition and update the farthestDst accordingly
I tried to submit this, but I got Wrong Answer (failing test case not shown) despite running successfully against some sample test cases. I have attached my code in C++ below
class TreeNode{
public:
// farthestDst is the index of the smallest element which is farthest away from it's right side
int val,idx,farthestDst;
TreeNode* left;
TreeNode* right;
TreeNode(int value, int index, int dst){
val = value;
idx = index;
farthestDst = dst;
left = right = NULL;
}
};
class Solution{
public:
TreeNode* root = NULL;
unordered_map <int,TreeNode*> mp; // store address of each node just to speed up search
TreeNode* insertBST(TreeNode* root, int val, int idx, int dst){
if(root == NULL){
TreeNode* node = new TreeNode(val,idx,dst);
mp[val] = node;
return node;
}
else if(val >= root->val){ // checking the condition
if((root->idx)-idx > dst){
dst = root->idx;
}
root->right = insertBST(root->right,val,idx,dst);
}
else{
root->left = insertBST(root->left,val,idx,dst);
}
return root;
}
// actual function to complete where N is the size of the vector and nums contains the values
vector<int> farNumber(int N,vector<int> nums){
vector<int> res;
if(nums.size() == 0){ // base case check if nums is empty
return res;
}
for(int i = nums.size()-1; i >= 0; i--){
root = insertBST(root,nums[i],i,-1);
}
for(int i = 0; i < nums.size(); i++){
TreeNode* node = mp[nums[i]];
res.push_back(node->farthestDst);
}
return res;
}
};
Just a note, if anyone wants to test their solution, they can do so at this link
Please do let me know if further clarification about the code is needed
Any help would be appreciated. Thanks!
mp[] assumes that each element value appears at most once in the input. This is not given as part of the problem description, so it's not guaranteed. If some value appears more than once, its original value in mp[] will be overwritten. (Ironically, most C++ standard libraries implement unordered_map<T> as a balanced BST -- an AVL tree or red-black tree.)
Not technically a bug, but as pointed out by nice_dev in a comment, because your BST performs no rebalancing, it can become arbitrarily badly balanced, leading to O(n) insertion times for O(n^2) performance overall. This will occur on, e.g, sorted or reverse-sorted inputs. There are probably test cases large enough to cause timeouts for O(n^2)-time algorithms.
Unfortunately, adding rebalancing to your code to bring the worst-case time down to O(n log n) will cause it to become incorrect, because it currently depends on a delicate property: It doesn't compare each inserted element with all smaller-valued elements to its right, but only with the ones you encounter on the path down from the root of the BST. Whenever during this traversal you encounter an element at position j with value nums[j] < nums[i], you ignore all elements in its left subtree. With your current implementation, this is safe: Although these elements are all known to be smaller than nums[i] by the BST property, they can't be further to the right than j is, because insertion order means that every child is to the left of its parent. But if you change the algorithm to perform tree rotations to rebalance the tree, the second property can be lost -- you could miss some element at position k with nums[k] < nums[j] < nums[i] but k > j.
Finally, having both a member variable root and a function argument root is confusing.

Deleting linked list nodes without recursion [duplicate]

I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.
So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help.
Are there general rules?
Is there a "pattern"?
Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.
var stack = [];
stack.push(firstObject);
// while not empty
while (stack.length) {
// Pop off end of stack.
obj = stack.pop();
// Do stuff.
// Push other objects on the stack as needed.
...
}
Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:
foo(first);
foo(second);
has to be replaced by
stack.push(second);
stack.push(first);
Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.
Really, the most common way to do it is to keep your own stack. Here's a recursive quicksort function in C:
void quicksort(int* array, int left, int right)
{
if(left >= right)
return;
int index = partition(array, left, right);
quicksort(array, left, index - 1);
quicksort(array, index + 1, right);
}
Here's how we could make it iterative by keeping our own stack:
void quicksort(int *array, int left, int right)
{
int stack[1024];
int i=0;
stack[i++] = left;
stack[i++] = right;
while (i > 0)
{
right = stack[--i];
left = stack[--i];
if (left >= right)
continue;
int index = partition(array, left, right);
stack[i++] = left;
stack[i++] = index - 1;
stack[i++] = index + 1;
stack[i++] = right;
}
}
Obviously, this example doesn't check stack boundaries... and really you could size the stack based on the worst case given left and and right values. But you get the idea.
It seems nobody has addressed where the recursive function calls itself more than once in the body, and handles returning to a specific point in the recursion (i.e. not primitive-recursive). It is said that every recursion can be turned into iteration, so it appears that this should be possible.
I just came up with a C# example of how to do this. Suppose you have the following recursive function, which acts like a postorder traversal, and that AbcTreeNode is a 3-ary tree with pointers a, b, c.
public static void AbcRecursiveTraversal(this AbcTreeNode x, List<int> list) {
if (x != null) {
AbcRecursiveTraversal(x.a, list);
AbcRecursiveTraversal(x.b, list);
AbcRecursiveTraversal(x.c, list);
list.Add(x.key);//finally visit root
}
}
The iterative solution:
int? address = null;
AbcTreeNode x = null;
x = root;
address = A;
stack.Push(x);
stack.Push(null)
while (stack.Count > 0) {
bool #return = x == null;
if (#return == false) {
switch (address) {
case A://
stack.Push(x);
stack.Push(B);
x = x.a;
address = A;
break;
case B:
stack.Push(x);
stack.Push(C);
x = x.b;
address = A;
break;
case C:
stack.Push(x);
stack.Push(null);
x = x.c;
address = A;
break;
case null:
list_iterative.Add(x.key);
#return = true;
break;
}
}
if (#return == true) {
address = (int?)stack.Pop();
x = (AbcTreeNode)stack.Pop();
}
}
Strive to make your recursive call Tail Recursion (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.
Well, in general, recursion can be mimicked as iteration by simply using a storage variable. Note that recursion and iteration are generally equivalent; one can almost always be converted to the other. A tail-recursive function is very easily converted to an iterative one. Just make the accumulator variable a local one, and iterate instead of recurse. Here's an example in C++ (C were it not for the use of a default argument):
// tail-recursive
int factorial (int n, int acc = 1)
{
if (n == 1)
return acc;
else
return factorial(n - 1, acc * n);
}
// iterative
int factorial (int n)
{
int acc = 1;
for (; n > 1; --n)
acc *= n;
return acc;
}
Knowing me, I probably made a mistake in the code, but the idea is there.
Even using stack will not convert a recursive algorithm into iterative. Normal recursion is function based recursion and if we use stack then it becomes stack based recursion. But its still recursion.
For recursive algorithms, space complexity is O(N) and time complexity is O(N).
For iterative algorithms, space complexity is O(1) and time complexity is O(N).
But if we use stack things in terms of complexity remains same. I think only tail recursion can be converted into iteration.
The stacks and recursion elimination article captures the idea of externalizing the stack frame on heap, but does not provide a straightforward and repeatable way to convert. Below is one.
While converting to iterative code, one must be aware that the recursive call may happen from an arbitrarily deep code block. Its not just the parameters, but also the point to return to the logic that remains to be executed and the state of variables which participate in subsequent conditionals, which matter. Below is a very simple way to convert to iterative code with least changes.
Consider this recursive code:
struct tnode
{
tnode(int n) : data(n), left(0), right(0) {}
tnode *left, *right;
int data;
};
void insertnode_recur(tnode *node, int num)
{
if(node->data <= num)
{
if(node->right == NULL)
node->right = new tnode(num);
else
insertnode(node->right, num);
}
else
{
if(node->left == NULL)
node->left = new tnode(num);
else
insertnode(node->left, num);
}
}
Iterative code:
// Identify the stack variables that need to be preserved across stack
// invocations, that is, across iterations and wrap them in an object
struct stackitem
{
stackitem(tnode *t, int n) : node(t), num(n), ra(0) {}
tnode *node; int num;
int ra; //to point of return
};
void insertnode_iter(tnode *node, int num)
{
vector<stackitem> v;
//pushing a stackitem is equivalent to making a recursive call.
v.push_back(stackitem(node, num));
while(v.size())
{
// taking a modifiable reference to the stack item makes prepending
// 'si.' to auto variables in recursive logic suffice
// e.g., instead of num, replace with si.num.
stackitem &si = v.back();
switch(si.ra)
{
// this jump simulates resuming execution after return from recursive
// call
case 1: goto ra1;
case 2: goto ra2;
default: break;
}
if(si.node->data <= si.num)
{
if(si.node->right == NULL)
si.node->right = new tnode(si.num);
else
{
// replace a recursive call with below statements
// (a) save return point,
// (b) push stack item with new stackitem,
// (c) continue statement to make loop pick up and start
// processing new stack item,
// (d) a return point label
// (e) optional semi-colon, if resume point is an end
// of a block.
si.ra=1;
v.push_back(stackitem(si.node->right, si.num));
continue;
ra1: ;
}
}
else
{
if(si.node->left == NULL)
si.node->left = new tnode(si.num);
else
{
si.ra=2;
v.push_back(stackitem(si.node->left, si.num));
continue;
ra2: ;
}
}
v.pop_back();
}
}
Notice how the structure of the code still remains true to the recursive logic and modifications are minimal, resulting in less number of bugs. For comparison, I have marked the changes with ++ and --. Most of the new inserted blocks except v.push_back, are common to any converted iterative logic
void insertnode_iter(tnode *node, int num)
{
+++++++++++++++++++++++++
vector<stackitem> v;
v.push_back(stackitem(node, num));
while(v.size())
{
stackitem &si = v.back();
switch(si.ra)
{
case 1: goto ra1;
case 2: goto ra2;
default: break;
}
------------------------
if(si.node->data <= si.num)
{
if(si.node->right == NULL)
si.node->right = new tnode(si.num);
else
{
+++++++++++++++++++++++++
si.ra=1;
v.push_back(stackitem(si.node->right, si.num));
continue;
ra1: ;
-------------------------
}
}
else
{
if(si.node->left == NULL)
si.node->left = new tnode(si.num);
else
{
+++++++++++++++++++++++++
si.ra=2;
v.push_back(stackitem(si.node->left, si.num));
continue;
ra2: ;
-------------------------
}
}
+++++++++++++++++++++++++
v.pop_back();
}
-------------------------
}
Search google for "Continuation passing style." There is a general procedure for converting to a tail recursive style; there is also a general procedure for turning tail recursive functions into loops.
Just killing time... A recursive function
void foo(Node* node)
{
if(node == NULL)
return;
// Do something with node...
foo(node->left);
foo(node->right);
}
can be converted to
void foo(Node* node)
{
if(node == NULL)
return;
// Do something with node...
stack.push(node->right);
stack.push(node->left);
while(!stack.empty()) {
node1 = stack.pop();
if(node1 == NULL)
continue;
// Do something with node1...
stack.push(node1->right);
stack.push(node1->left);
}
}
Thinking of things that actually need a stack:
If we consider the pattern of recursion as:
if(task can be done directly) {
return result of doing task directly
} else {
split task into two or more parts
solve for each part (possibly by recursing)
return result constructed by combining these solutions
}
For example, the classic Tower of Hanoi
if(the number of discs to move is 1) {
just move it
} else {
move n-1 discs to the spare peg
move the remaining disc to the target peg
move n-1 discs from the spare peg to the target peg, using the current peg as a spare
}
This can be translated into a loop working on an explicit stack, by restating it as:
place seed task on stack
while stack is not empty
take a task off the stack
if(task can be done directly) {
Do it
} else {
Split task into two or more parts
Place task to consolidate results on stack
Place each task on stack
}
}
For Tower of Hanoi this becomes:
stack.push(new Task(size, from, to, spare));
while(! stack.isEmpty()) {
task = stack.pop();
if(task.size() = 1) {
just move it
} else {
stack.push(new Task(task.size() -1, task.spare(), task,to(), task,from()));
stack.push(new Task(1, task.from(), task.to(), task.spare()));
stack.push(new Task(task.size() -1, task.from(), task.spare(), task.to()));
}
}
There is considerable flexibility here as to how you define your stack. You can make your stack a list of Command objects that do sophisticated things. Or you can go the opposite direction and make it a list of simpler types (e.g. a "task" might be 4 elements on a stack of int, rather than one element on a stack of Task).
All this means is that the memory for the stack is in the heap rather than in the Java execution stack, but this can be useful in that you have more control over it.
Generally the technique to avoid stack overflow is for recursive functions is called trampoline technique which is widely adopted by Java devs.
However, for C# there is a little helper method here that turns your recursive function to iterative without requiring to change logic or make the code in-comprehensible. C# is such a nice language that amazing stuff is possible with it.
It works by wrapping parts of the method by a helper method. For example the following recursive function:
int Sum(int index, int[] array)
{
//This is the termination condition
if (int >= array.Length)
//This is the returning value when termination condition is true
return 0;
//This is the recursive call
var sumofrest = Sum(index+1, array);
//This is the work to do with the current item and the
//result of recursive call
return array[index]+sumofrest;
}
Turns into:
int Sum(int[] ar)
{
return RecursionHelper<int>.CreateSingular(i => i >= ar.Length, i => 0)
.RecursiveCall((i, rv) => i + 1)
.Do((i, rv) => ar[i] + rv)
.Execute(0);
}
One pattern to look for is a recursion call at the end of the function (so called tail-recursion). This can easily be replaced with a while. For example, the function foo:
void foo(Node* node)
{
if(node == NULL)
return;
// Do something with node...
foo(node->left);
foo(node->right);
}
ends with a call to foo. This can be replaced with:
void foo(Node* node)
{
while(node != NULL)
{
// Do something with node...
foo(node->left);
node = node->right;
}
}
which eliminates the second recursive call.
A question that had been closed as a duplicate of this one had a very specific data structure:
The node had the following structure:
typedef struct {
int32_t type;
int32_t valueint;
double valuedouble;
struct cNODE *next;
struct cNODE *prev;
struct cNODE *child;
} cNODE;
The recursive deletion function looked like:
void cNODE_Delete(cNODE *c) {
cNODE*next;
while (c) {
next=c->next;
if (c->child) {
cNODE_Delete(c->child)
}
free(c);
c=next;
}
}
In general, it is not always possible to avoid a stack for recursive functions that invoke itself more than one time (or even once). However, for this particular structure, it is possible. The idea is to flatten all the nodes into a single list. This is accomplished by putting the current node's child at the end of the top row's list.
void cNODE_Delete (cNODE *c) {
cNODE *tmp, *last = c;
while (c) {
while (last->next) {
last = last->next; /* find last */
}
if ((tmp = c->child)) {
c->child = NULL; /* append child to last */
last->next = tmp;
tmp->prev = last;
}
tmp = c->next; /* remove current */
free(c);
c = tmp;
}
}
This technique can be applied to any data linked structure that can be reduce to a DAG with a deterministic topological ordering. The current nodes children are rearranged so that the last child adopts all of the other children. Then the current node can be deleted and traversal can then iterate to the remaining child.
Recursion is nothing but the process of calling of one function from the other only this process is done by calling of a function by itself. As we know when one function calls the other function the first function saves its state(its variables) and then passes the control to the called function. The called function can be called by using the same name of variables ex fun1(a) can call fun2(a).
When we do recursive call nothing new happens. One function calls itself by passing the same type and similar in name variables(but obviously the values stored in variables are different,only the name remains same.)to itself. But before every call the function saves its state and this process of saving continues. The SAVING IS DONE ON A STACK.
NOW THE STACK COMES INTO PLAY.
So if you write an iterative program and save the state on a stack each time and then pop out the values from stack when needed, you have successfully converted a recursive program into an iterative one!
The proof is simple and analytical.
In recursion the computer maintains a stack and in iterative version you will have to manually maintain the stack.
Think over it, just convert a depth first search(on graphs) recursive program into a dfs iterative program.
All the best!
TLDR
You can compare the source code below, before and after to intuitively understand the approach without reading this whole answer.
I ran into issues with some multi-key quicksort code I was using to process very large blocks of text to produce suffix arrays. The code would abort due to the extreme depth of recursion required. With this approach, the termination issues were resolved. After conversion the maximum number of frames required for some jobs could be captured, which was between 10K and 100K, taking from 1M to 6M memory. Not an optimum solution, there are more effective ways to produce suffix arrays. But anyway, here's the approach used.
The approach
A general way to convert a recursive function to an iterative solution that will apply to any case is to mimic the process natively compiled code uses during a function call and the return from the call.
Taking an example that requires a somewhat involved approach, we have the multi-key quicksort algorithm. This function has three successive recursive calls, and after each call, execution begins at the next line.
The state of the function is captured in the stack frame, which is pushed onto the execution stack. When sort() is called from within itself and returns, the stack frame present at the time of the call is restored. In that way all the variables have the same values as they did before the call - unless they were modified by the call.
Recursive function
def sort(a: list_view, d: int):
if len(a) <= 1:
return
p = pivot(a, d)
i, j = partition(a, d, p)
sort(a[0:i], d)
sort(a[i:j], d + 1)
sort(a[j:len(a)], d)
Taking this model, and mimicking it, a list is set up to act as the stack. In this example tuples are used to mimic frames. If this were encoded in C, structs could be used. The data can be contained within a data structure instead of just pushing one value at a time.
Reimplemented as "iterative"
# Assume `a` is view-like object where slices reference
# the same internal list of strings.
def sort(a: list_view):
stack = []
stack.append((LEFT, a, 0)) # Initial frame.
while len(stack) > 0:
frame = stack.pop()
if len(frame[1]) <= 1: # Guard.
continue
stage = frame[0] # Where to jump to.
if stage == LEFT:
_, a, d = frame # a - array/list, d - depth.
p = pivot(a, d)
i, j = partition(a, d, p)
stack.append((MID, a, i, j, d)) # Where to go after "return".
stack.append((LEFT, a[0:i], d)) # Simulate function call.
elif stage == MID: # Picking up here after "call"
_, a, i, j, d = frame # State before "call" restored.
stack.append((RIGHT, a, i, j, d)) # Set up for next "return".
stack.append((LEFT, a[i:j], d + 1)) # Split list and "recurse".
elif stage == RIGHT:
_, a, _, j, d = frame
stack.append((LEFT, a[j:len(a)], d)
else:
pass
When a function call is made, information on where to begin execution after the function returns is included in the stack frame. In this example, if/elif/else blocks represent the points where execution begins after return from a call. In C this could be implemented as a switch statement.
In the example, the blocks are given labels; they're arbitrarily labeled by how the list is partitioned within each block. The first block, "LEFT" splits the list on the left side. The "MID" section represents the block that splits the list in the middle, etc.
With this approach, mimicking a call takes two steps. First a frame is pushed onto the stack that will cause execution to resume in the block following the current one after the "call" "returns". A value in the frame indicates which if/elif/else section to fall into on the loop that follows the "call".
Then the "call" frame is pushed onto the stack. This sends execution to the first, "LEFT", block in most cases for this specific example. This is where the actual sorting is done regardless which section of the list was split to get there.
Before the looping begins, the primary frame pushed at the top of the function represents the initial call. Then on each iteration, a frame is popped. The "LEFT/MID/RIGHT" value/label from the frame is used to fall into the correct block of the if/elif/else statement. The frame is used to restore the state of the variables needed for the current operation, then on the next iteration the return frame is popped, sending execution to the subsequent section.
Return values
If the recursive function returns a value used by itself, it can be treated the same way as other variables. Just create a field in the stack frame for it. If a "callee" is returning a value, it checks the stack to see if it has any entries; and if so, updates the return value in the frame on the top of the stack. For an example of this you can check this other example of this same approach to recursive to iterative conversion.
Conclusion
Methods like this that convert recursive functions to iterative functions, are essentially also "recursive". Instead of the process stack being utilized for actual function calls, another programmatically implemented stack takes its place.
What is gained? Perhaps some marginal improvements in speed. Or it could serve as a way to get around stack limitations imposed by some compilers and/or execution environments (stack pointer hitting the guard page). In some cases, the amount of data pushed onto the stack can be reduced. Do the gains offset the complexity introduced in the code by mimicking something that we get automatically with the recursive implementation?
In the case of the sorting algorithm, finding a way to implement this particular one without a stack could be challenging, plus there are so many iterative sorting algorithms available that are much faster. It's been said that any recursive algorithm can be implemented iteratively. Sure... but some algorithms don't convert well without being modified to such a degree that they're no longer the same algorithm.
It may not be such a great idea to convert recursive algorithms just for the sake of converting them. Anyway, for what it's worth, the above approach is a generic way of converting that should apply to just about anything.
If you find you really need an iterative version of a recursive function that doesn't use a memory eating stack of its own, the best approach may be to scrap the code and write your own using the description from a scholarly article, or work it out on paper and then code it from scratch, or other ground up approach.
There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.
Another simple and complete example of turning the recursive function into iterative one using the stack.
#include <iostream>
#include <stack>
using namespace std;
int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); }
struct Par
{
int a, b;
Par() : Par(0, 0) {}
Par(int _a, int _b) : a(_a), b(_b) {}
};
int GCDIter(int a, int b)
{
stack<Par> rcstack;
if (b == 0)
return a;
rcstack.push(Par(b, a % b));
Par p;
while (!rcstack.empty())
{
p = rcstack.top();
rcstack.pop();
if (p.b == 0)
continue;
rcstack.push(Par(p.b, p.a % p.b));
}
return p.a;
}
int main()
{
//cout << GCD(24, 36) << endl;
cout << GCDIter(81, 36) << endl;
cin.get();
return 0;
}
My examples are in Clojure, but should be fairly easy to translate to any language.
Given this function that StackOverflows for large values of n:
(defn factorial [n]
(if (< n 2)
1
(*' n (factorial (dec n)))))
we can define a version that uses its own stack in the following manner:
(defn factorial [n]
(loop [n n
stack []]
(if (< n 2)
(return 1 stack)
;; else loop with new values
(recur (dec n)
;; push function onto stack
(cons (fn [n-1!]
(*' n n-1!))
stack)))))
where return is defined as:
(defn return
[v stack]
(reduce (fn [acc f]
(f acc))
v
stack))
This works for more complex functions too, for example the ackermann function:
(defn ackermann [m n]
(cond
(zero? m)
(inc n)
(zero? n)
(recur (dec m) 1)
:else
(recur (dec m)
(ackermann m (dec n)))))
can be transformed into:
(defn ackermann [m n]
(loop [m m
n n
stack []]
(cond
(zero? m)
(return (inc n) stack)
(zero? n)
(recur (dec m) 1 stack)
:else
(recur m
(dec n)
(cons #(ackermann (dec m) %)
stack)))))
A rough description of how a system takes any recursive function and executes it using a stack:
This intended to show the idea without details. Consider this function that would print out nodes of a graph:
function show(node)
0. if isleaf(node):
1. print node.name
2. else:
3. show(node.left)
4. show(node)
5. show(node.right)
For example graph:
A->B
A->C
show(A) would print B, A, C
Function calls mean save the local state and the continuation point so you can come back, and then jump the the function you want to call.
For example, suppose show(A) begins to run. The function call on line 3. show(B) means
- Add item to the stack meaning "you'll need to continue at line 2 with local variable state node=A"
- Goto line 0 with node=B.
To execute code, the system runs through the instructions. When a function call is encountered, the system pushes information it needs to come back to where it was, runs the function code, and when the function completes, pops the information about where it needs to go to continue.
This link provides some explanation and proposes the idea of keeping "location" to be able to get to the exact place between several recursive calls:
However, all these examples describe scenarios in which a recursive call is made a fixed amount of times. Things get trickier when you have something like:
function rec(...) {
for/while loop {
var x = rec(...)
// make a side effect involving return value x
}
}
This is an old question but I want to add a different aspect as a solution. I'm currently working on a project in which I used the flood fill algorithm using C#. Normally, I implemented this algorithm with recursion at first, but obviously, it caused a stack overflow. After that, I changed the method from recursion to iteration. Yes, It worked and I was no longer getting the stack overflow error. But this time, since I applied the flood fill method to very large structures, the program was going into an infinite loop. For this reason, it occurred to me that the function may have re-entered the places it had already visited. As a definitive solution to this, I decided to use a dictionary for visited points. If that node(x,y) has already been added to the stack structure for the first time, that node(x,y) will be saved in the dictionary as the key. Even if the same node is tried to be added again later, it won't be added to the stack structure because the node is already in the dictionary. Let's see on pseudo-code:
startNode = pos(x,y)
Stack stack = new Stack();
Dictionary visited<pos, bool> = new Dictionary();
stack.Push(startNode);
while(stack.count != 0){
currentNode = stack.Pop();
if "check currentNode if not available"
continue;
if "check if already handled"
continue;
else if "run if it must be wanted thing should be handled"
// make something with pos currentNode.X and currentNode.X
// then add its neighbor nodes to the stack to iterate
// but at first check if it has already been visited.
if(!visited.Contains(pos(x-1,y)))
visited[pos(x-1,y)] = true;
stack.Push(pos(x-1,y));
if(!visited.Contains(pos(x+1,y)))
...
if(!visited.Contains(pos(x,y+1)))
...
if(!visited.Contains(pos(x,y-1)))
...
}

find nth element from the last in a list using recursion

we can solve this problem in, say C, using a static variable, like in the snippet below (like the function found in this page).
static int i = 0;
if(head == NULL)
return;
getNthFromLast(head->next, n);
if(++i == n)
{THIS IS THE NTH ELEM FROM LAST
DO STUFF WITH IT.
}
I'm trying to see if I can solve this using a tail call recursion,
and NO static variables/global variables.
I'm trying to learn Haskell was wondering how to implement this in a purely functional way, with out using Haskell's length and
!! something like x !! ((length x) - K).
So started by asking, how we can do it in C, with recursion and NO static/global variables, just to get some idea.
Any suggestions/pointers would be appreciated.
Thanks.
The linked page explains how to solve the problem with a two-finger solution; it's a bit surprising that they don't simply write the recursive version, which would be simple and clear. (In my experience, you don't succeed at interviews by providing tricky and obscure code when there is a simple and clear version which is equally efficient. But I suppose there are interviewers who value obscure code.)
So, the two-finger solution is based on the observation that if we have two pointers into the list (the two fingers), and they are always n elements apart because we always advance them in tandem, then when the leading finger reaches the end of the list, the trailing finger will point at the element we want. That's an easy tail recursion:
Node* tandem_advance(Node* leading, Node* trailing) {
return leading ? tandem_advance(leading->next, trailing->next)
: trailing;
}
For the initial case, we need the leading finger to be N elements from the beginning of the list. Another simple tail recursion:
Node* advance_n(Node* head, int n) {
return n ? advance_n(head->next, n - 1)
: head;
}
Then we just need to put the two together:
Node* nth_from_end(Node* head, int n) {
return tandem_advance(advance_n(head, n + 1), head);
}
(We initially advance by n+1 so that the 0th node from the end will be the last node. I didn't check the desired semantics; it might be that n would be correct instead.)
In Haskell, the two-finger solution seems to be the obvious way. This version will go wrong in various ways if the requested element isn't present. I'll leave it as an exercise for you to fix that (hint: write versions of drop and last that return Maybe values, and then string the computations together with >>=). Note that this takes the last element of the list to be 0th from the end.
nthFromLast :: Int -> [a] -> a
nthFromLast n xs = last $ zipWith const xs (drop n xs)
If you want to do some of the recursion by hand, which No_signal indicates gives better performance,
-- The a and b types are different to make it clear
-- which list we get the value from.
lzc :: [a] -> [b] -> a
lzc [] _ = error "Empty list"
lzc (x : _xs) [] = x
lzc (_x : xs) (_y : ys) = lzc xs ys
nthFromLast n xs = lzc xs (drop n xs)
We don't bother writing out drop by hand because the rather simple-minded version in the library is about the best possible. Unlike either the first solution in this answer or the "reverse, then index" approach, the implementation using lzc only needs to allocate a constant amount of memory.
I assume your code is missing
getNthFromLast(list *node_ptr, int n) {
right at the top. (!!)
Your recursive version keeps track of node_ptrs in its call stack frames, so it is essentially non tail-recursive. Moreover, it continues to unwind the stack (go back up the stack of call frames), while incrementing the i and still checking its equality to n, even after it had found its goal nth node from the last; so it is not efficient.
That would be an iterative version, indeed encodable as tail-recursive, that does things on the way forward, and so can stop immediately after reaching its target. For that, we open up the n-length gap from the start, not after the end is reached. Instead of counting backwards as your recursive version does, we count forward. This is the same two-pointers approach already mentioned here.
In pseudocode,
end = head;
repeat n: (end = end->next);
return tailrec(head,end)->payload;
where
tailrec(p,q) {
if(NULL==q): return p;
else: tailrec(p->next, q->next);
}
This is 1-based, assuming n <= length(head). Haskell code is already given in another answer.
This technique is known as tail recursion modulo cons, or here, modulo payload-access.
nthFromLast lst n = reverse lst !! n
Because Haskell is lazy, this should be sufficiently efficient
If you don't want to use !!, you'll have to redefine it yourself, but this is silly.
The typical iterative strategy uses two pointers and runs one to n - 1 before starting to move the other.
With recursion, we can instead use the stack to count back up from the end of the list by adding a third argument. And to keep the usage clean, we can make a static helper function (in this sense it means only visible within compilation unit, a totally different concept to a static variable with function scope).
static node *nth_last_helper(node* curr, unsigned int n, unsigned int *f) {
node *t;
if (!curr) {
*f = 1;
return NULL;
}
t = nth_last_helper(curr->next, n, f);
if (n == (*f)++) return curr;
return t;
}
node* nth_last(node* curr, unsigned int n) {
unsigned int finder = 0;
return nth_last_helper(curr, n, &finder);
}
Alternatively we could actually do the counting without the extra parameter, but I think this is less clear.
static node *nth_last_helper(node* curr, unsigned int *n) {
node *t;
if (!curr) return NULL;
t = nth_last_helper(curr->next, n);
if (t) return t;
if (1 == (*n)--) return curr;
return NULL;
}
node* nth_last(node* curr, unsigned int n) {
return nth_last_helper(curr, &n);
}
Note that I have used unsigned integers to avoid choosing semantics for the "negative nth last" value in a list.
However, neither of these are tail recursive. To achieve that, you can more directly convert the iterative solution into a recursive one, as in rici's answer.

Efficiently choose an integer distinct from all elements of a list

I have a linked list of objects each containing a 32-bit integer (and provably fewer than 232 such objects) and I want to efficiently choose an integer that's not present in the list, without using any additional storage (so copying them to an array, sorting the array, and choosing the minimum value not in the array would not be an option). However, the definition of the structure for list elements is under my control, so I could add (within reason) additional storage to each element as part of solving the problem. For example, I could add an extra set of prev/next pointers and merge-sort the list. Is this the best solution? Or is there a simpler or more efficient way to do it?
Given the conditions that you outline in the comments, especially your expectation of many identical values, you must expect a sparse distribution of used values.
Consequently, it might actually be best to just guess a value randomly and then check whether it coincides with a value in the list. Even if half the available value range were used (which seems extremely unlikely from your comments), you would only traverse the list twice on average. And you can drastically decrease this factor by simultaneously checking a number of guesses in one pass. Done correctly, the factor should always be close to one.
The advantage of such a probabilistic approach is that you are immune to bad sequences of values. Such sequences are always possible with range based approaches: If you calculate the min and max of the data, you run the risk, that the data contains both 0 and 2^32-1. If you sequentially subdivide an interval, you run the risk of always getting values in the middle of the interval, which can shrink it to zero in 32 steps. With a probabilistic approach, these sequences can't hurt you.
I think, I would use something like four guesses for very small lists, and crank it up to roughly 16 as the size of the list approaches the limit. The high starting value is due to the fact that any such algorithm will be memory bound, i. e. your CPU has ample amounts of time to check a value while it waits for the next values to arrive from memory, so you better make good use of that time to reduce the number of passes required.
A further optimization would instantly replace a busted guess with a new one and keep track of where the replacement happened, so that you can avoid a complete second pass through the data. Also, move the busted guess to the end of the list of guesses, so that you only need to check against the start position of the first guess in your loop to stop as early as possible.
If you can spare one pointer in each object, you get an O(n) worst-case algorithm easily (standard divide-and-conquer):
Divide the range of possible IDs equally.
Make a singly-linked list covering each subrange.
If one subrange is empty, choose any id in it.
Otherwise repeat with the elements of the subrange with fewest elements.
Example code using two sub-ranges per iteration:
unsigned getunusedid(element* h) {
unsigned start = 0, stop = -1;
for(;h;h = h->mainnext)
h->next = h->mainnext;
while(h) {
element *l = 0, *r = 0;
unsigned cl = 0, cr = 0;
unsigned mid = start + (stop - start) / 2;
while(h) {
element* next = h->next;
if(h->id < mid) {
h->next = l;
cl++;
l = h;
} else {
h->next = r;
cr++;
r = h;
}
h = next;
}
if(cl < cr) {
h = l;
stop = mid - 1;
} else {
h = r;
start = mid;
}
}
return start;
}
Some more remarks:
Beware of bugs in the above code; I have only proved it correct, not tried it.
Using more buckets (best keep to a power of 2 for easy and efficient handling) each iteration might be faster due to better data-locality (though only try and measure if it's not fast enough otherwise), as #MarkDickson rightly remarks.
Without those extra-pointers, you need full sweeps each iteration, raising the bound to O(n*lg n).
An alternative would be using 2+ extra-pointers per element to maintain a balanced tree. That would speed up id-search, at the expense of some memory and insertion/removal time overhead.
If you don't mind an O(n) scan for each change in the list and two extra bits per element, whenever an element is inserted or removed, scan through and use the two bits to represent whether an integer (element + 1) or (element - 1) exists in the list.
For example, inserting the element, 2, the extra bits for each 3 and 1 in the list would be updated to show that 3-1 (in the case of 3) and 1+1 (in the case of 1) now exist in the list.
Insertion/deletion time can be reduced by adding a pointer from each element to the next element with the same integer.
I am supposing that integers have random values not controlled by your code.
Add two unsigned integers in your list class:
unsigned int rangeMinId = 0;
unsigned int rangeMaxId = 0xFFFFFFFF ;
Or if not possible to change the List class add them as global variables.
When the list is empty you will always know that the range if free. When you add a new item in the list check if its ID is between rangeMinId and rangeMaxId and if so change the nearest of them to this ID.
It may happen after a lot of time that rangeMinId to become equal to rangeMaxId-1, then you need a simple function which traverses the whole list and search for another free range. But this will not happens very frequently.
Other solutions are more complex and involves using of sets, binary trees or sorted arrays.
Update:
The free range search function can be done in O(n*log(n)). An example of such function is given below(I have not extensively tested it). The example is for integer array but easily can be adapted for a list.
int g_Calls = 0;
bool _findFreeRange(const int* value, int n, int& left, int& right)
{
g_Calls ++ ;
int l=left, r=right,l2,r2;
int m = (right + left) / 2 ;
int nl=0, nr=0;
for(int k = 0; k < n; k++)
{
const int& i = value[k] ;
if(i > l && i < r)
{
if(i-l < r-i)
l = i;
else
r = i;
}
if(i < m)
nl ++ ;
else
nr ++ ;
}
if ( (r - l) > 1 )
{
left = l;
right = r;
return true ;
}
if( nl < nr)
{
// check first left then right
l2 = left;
r2 = m;
if(r2-l2 > 1 && _findFreeRange(value, n, l2, r2))
{
left = l2 ;
right = r2 ;
return true;
}
l2 = m;
r2 = right;
if(r2-l2 > 1 && _findFreeRange(value, n, l2, r2))
{
left = l2 ;
right = r2 ;
return true;
}
}
else
{
// check first right then left
l2 = m;
r2 = right;
if(r2-l2 > 1 && _findFreeRange(value, n, l2, r2))
{
left = l2 ;
right = r2 ;
return true;
}
l2 = left;
r2 = m;
if(r2-l2 > 1 && _findFreeRange(value, n, l2, r2))
{
left = l2 ;
right = r2 ;
return true;
}
}
return false;
}
bool findFreeRange(const int* value, int n, int& left, int& right, int maxx)
{
g_Calls = 1;
left = 0;
right = maxx;
if(!_findFreeRange(value, n, left, right))
return false ;
left++;
right--;
return (right - left) >= 0 ;
}
If it returns false list is filled and there is no free range (very least possible), maxm is the maximal limit of the range in this case 0xFFFFFFFF.
The idea is first to search the biggest range of the list and then if no free hole is found to recursively search the subranges for holes which may have been left during the first pass. If the list is sparsely filled it is very least probable that function will be called more than once. However when the list become almost completely filled it can happen the range search to take longer. Thus in this most worst case scenario, when the list becomes closed to filled, its better to start keeping all free ranges in a list.
This reminds me of the book Programming Pearls, and in particular the very first column, "Cracking the Oyster". What is the real problem you are trying to solve?
If your list is small, then a simple linear search to find max/min would work and it would work quickly.
When your list gets large and linear search becomes unwieldy, you can build a bitmap to represent the unused numbers for much less memory than adding 2 extra pointers at each node in the linked list. In fact, it would only be 2^(32-8) = 16KB of RAM compared to your linked list being potentially >10GB.
Then to find an unused number, you can just traverse the bitmap one machine-word at a time, checking if it's non-zero. If it is, then at least one number in that 32- or 64- bit block is unused, and you can inspect the word to find out exactly which bit is set. As you add numbers to the list, all you have to do is clear the corresponding bit in the bitmap.
One possible solution is to take the min and max of the list with a simple O(n) iteration, then pick a number between max and min + (1 << 32). This is simple to do since overflow/underflow behavior is well-defined for unsigned integers:
uint32_t min, max;
// TODO: compute min and max here
// exclude max from choice space (min will be an exclusive upper bound)
max++;
uint32_t choice = rand32() % (min - max) + max; // where rand32 is a random unsigned 32-bit integer
Of course, if it doesn't need to be random, then you can just use one more than the maximum of the list.
Note: the only case where this fails is if min is 0 and max is UINT32_MAX (aka 4294967295).
Ok. Here is one really simple solution. Some of the answers have become too theoretical and complicated for optimization. If you need a quick solution do this:
1.In your List add a member:
unsigned int NextFreeId = 1;
add also an std::set<unsigned int> ids
When you add item in the list add also the integer in the set and keep track of the NextFreeId:
int insert(unsigned int id)
{
ids.insert(id);
if (NextFreeId == id) //will not happen too frequently
{
unsigned int TheFreeId ;
unsigned int nextid = id+1, previd = id-1;
while(true )
{
if(nextid < 0xFFFFFFF && !ids.count(nextid))
{
NextFreeId = nextid ;
break ;
}
if(previd > 0 && !ids.count(previd))
{
NextFreeId = previd ;
break ;
}
if(prevId == 0 && nextid == 0xFFFFFFF)
break; // all the range is filled, there is no free id
nextid++ ;
previd -- ;
}
}
return 1;
}
Sets are very efficient to check if a value is contained so the complexity will be O(log(N)). It is quick to implement. Also set is searched not each time but only when the NextFreeId is filled. List is not traversed at all.

How can I get a boolean out of a reiteration

I made this binary search using reiteration, however, when I get the answer (boolean), I seem to stumble in my way out of the reiteration and cant get the correct answer out of the function.
Can anybody help? Please comment on the code.
// binary search
bool
search(int value, int array[], int n)
{
// the array has more than 1 item
if (n > 1)
{
int m = (n/2);
// compares the middle point to the value
if (value == array [m])
return true;
// if the value given is lower than the middle point of the array
if (value < array [m])
{
int *new_array = malloc (m * sizeof(int));
// creating a new array with the lower half of the original one
memcpy(new_array, array, m * sizeof(int));
// recalling the function
search (value, new_array, m);
}
// if the value given is greater than the middle point of the array
else
{
int *new_array = malloc (m * sizeof(int));
// creating a new array with the upper half of the original one
memcpy(new_array, array + (m + 1), (m * sizeof(int)));
// recalling the function
search (value, new_array, m);
}
}
else if (n==1)
{
// comparing the one item array with the value
if (array[0] == value)
return true;
else
return false;
}
if (true)
return true;
else
return false;
}
You need to return the value of recursive searches.
return search (value, new_array, m);
Otherwise when you call search you are just throwing away the answer
You should return search(...);, and not only invoke the search() method - otherwise the return value is not bubbled up.
In addition, note that this algorithm is O(n) (linear in the size of the array) and is leaking memory and very inefficient, since you copy half of the array in each iteration.
Actually, It probably makes the algorithm much slower then the naive linear search for an element.
A good binary search does not need to copy half of the array - it just "looks" at half of it. It can be achieved by sending array+m as the array (for the higher half), and only decreasing n is enough for the lower half.
As mentioned by amint copying the array completely defeats the purpose of doing a binary search. Second, I believe you mean recursion, not reiteration.
Things to think about: Instead of copying the array, think about how you could achieve the same result by passing in a set of indexes to the array (like beginning and end).
As to your actual question, how to return the boolean value through the recursion. The thing about returning values out of a recursive function is that each iteration has to pass along the value. You can think of it like a chain of responsibility delegation. The first call is like the head of the company. He doesn't do all of the work, so he delegates it to his assistant but he does one piece of the work first. Then the assistant has an assistant etc. Turtles all the way down ;)
In order to get a value back though, each person in the chain has to give it back to the person before them. Going back to programming, this means that every time you recursively call search, you need to return that value.
Lastly, once you have those things in order you need to get your base case better defined. I assume that's what you're trying to do with
if (true)
return true;
else
return false;
However, as pointed out by H2CO3, this doesn't make much sense. In fact, your previous if statement if (n == 1) ... should make sure that the code after that is never executed.

Resources