Browsing the archives for the Programming category

Nth-to-Last Element in a Singly Linked List

Question: Devise an algorithm to determine the Nth-to-Last element in a singly linked list of unknown length. If N = 0, then your algorithm must return the last element. Answer: Given that the only way to traverse a singly linked list is forwards from the head, it is not possible to just count N elements […]

C Keywords – Review

Static Static keyword can be used for both variables and functions. By default, functions and global variables defined in a file are available for use in other files. However, if the static keyword is used, they are restricted to the current file only. They will not be available in other files even if the extern […]

Singly Linked List – Delete Node

Question: You are given a pointer to a node (not the tail node) in a┬ásingly┬álinked list. Delete that node from the linked list. Write code in C. Answer: To delete a node, you have to redirect the next pointer of the previous node to point to the next node instead of the current one. Since […]

Reverse a Linked-List

Question: Reverse a Linked-list. Write code in C. Answer: There are multiple ways to go about this. Let’s first look at a recursive solution. Node * reverse( Node * ptr , Node * previous) { Node * temp; if(ptr->next == NULL) { ptr->next = previous; return ptr; } else { temp = reverse(ptr->next, ptr); ptr->next […]

Sub-Array with the Largest Sum

Question: You are given an array with integers (both positive and negative) in any random order. Find the sub-array with the largest sum. Answer: This is an all-time favorite software interview question. The best way to solve this puzzle is to use Kadane’s algorithm which runs in O(n) time. The idea is to keep scanning […]