Kotlin linked list: How to check if given list is sorted (descending) - sorting

I am trying to write a function, which determines if the given linked list is sorted (descending).
Given list 1: 8 -> 5 -> 3 -> null (true)
Given list2: 8 -> 6 -> 10 -> 3 -> null (false)
Given list3: 8 -> 8 -> 3 -> null (true)
Here is my current approach:
class Linkedlist {
var head: Node? = null
data class Node(val value: Int, var next: Node?)
// Current approach
fun isListSorted(): Boolean {
// If list is empty
if (head == null) return true
var curr = head
while(curr != null) {
curr = curr.next
if (curr?.value!! <= curr?.next?.value!!) return false else return true
}
return true
}
}
And here my main:
fun main() {
val list1 = Linkedlist()
list1.append(8)
list1.append(5)
list1.append(3)
val list2 = Linkedlist()
list2.append(8)
list2.append(6)
list2.append(10)
list2.append(3)
val list3 = Linkedlist()
list3.append(8)
list3.append(8)
list3.append(3)
}
I get a NullPointerException. What am I doing wrong? I appreciate every help!

One of Kotlin's most attractive features is null-safety. You don't get NullPointerExceptions unless you use the !! operator. The !! operator should only be used when you have checked your code and you logically know that at that point in code, the parameter cannot be null, but the logic to figure that out is too much for the compiler.
You use the !! operator in a place where the value of curr very well can be null. You set curr = curr.next, and next will be null at the tail of your list, so curr will be null when you use the !! operator on it.
This line of code wouldn't make sense anyway, because you return from both branches of your if/else here, so you cannot possibly ever check more than one node of your list.
A possible way to do this:
fun isListSorted(): Boolean {
var curr = head ?: return true
while(true) {
val next = curr.next ?: return true
if (curr.value < next.value)
return false
curr = next
}
}

Related

Using recursion to get the sum of a tree, but the root node won't add in Kotlin

I'm doing a question to get the sum of an entire tree through recursion, but the root node wont add with the child node. Now I'm aware that the root node is just a value while the child nodes are Tree nodes, so there not the same type.
class TreeNode<T>(var key: T){
var left: TreeNode<T>? = null
var right: TreeNode<T>? = null
}
fun treeSumR(root: TreeNode<Int>): Int{
if (root == null) return 0
return root.key + root.left?.let { treeSumR(it) } + root.right?.let { treeSumR(it) }
}
fun buildTree2(): TreeNode<Int>{
val one = TreeNode(1)
val two = TreeNode(2)
val four = TreeNode(4)
val eleven = TreeNode(11)
val three = TreeNode(3)
val four2 = TreeNode(4)
three.left = eleven
three.right = four
eleven.left = four2
eleven.right = two
four.right = one
return three
}
Any help is appreciated. Thanks.
There is an error on the + operators because you are adding a non-nullable Int (root.key) and nullable Int?s (the sums of the subtrees) together. The sums of the subtrees are nullable because you wrote ?.. Its effect is that the whole expression of root.left?.let { ... } evaluates to null if root.left is null.
You can provide a default value for the expression when it is null by using the elvis operator:
return root.key +
(root.left?.let { treeSumR(it) } ?: 0) +
(root.right?.let { treeSumR(it) } ?: 0)
However, since you are already checking if root is null and returning 0, a better way is to make root actually nullable, and pass root.left and root.right directly into it treeSumR:
// notice the question mark here
// v
fun treeSumR(root: TreeNode<Int>?): Int{
if (root == null) return 0
return root.key +
treeSumR(root.left) + // since treeSumR now takes a nullable node, you can directly pass the subtrees in
treeSumR(root.right)
}

Given: aabcdddeabb => Expected: [(a,2),(b,1),(c,1),(d,3),(e,1),(a,1),(b,1)] in Scala

I'm really interested in how this algorithm can be implemented. If possible, it would be great to see an implementation with and without recursion. I am new to the language so I would be very grateful for help. All I could come up with was this code and it goes no further:
print(counterOccur("aabcdddeabb"))
def counterOccur(string: String) =
string.toCharArray.toList.map(char => {
if (!char.charValue().equals(char.charValue() + 1)) (char, counter)
else (char, counter + 1)
})
I realize that it's not even close to the truth, I just don't even have a clue what else could be used.
First solution with using recursion. I take Char by Char from string and check if last element in the Vector is the same as current. If elements the same I update last element by increasing count(It is first case). If last element does not the same I just add new element to the Vector(second case). When I took all Chars from the string I just return result.
def counterOccur(string: String): Vector[(Char, Int)] = {
#tailrec
def loop(str: List[Char], result: Vector[(Char, Int)]): Vector[(Char, Int)] = {
str match {
case x :: xs if result.lastOption.exists(_._1.equals(x)) =>
val count = result(result.size - 1)._2
loop(xs, result.updated(result.size - 1, (x, count + 1)))
case x :: xs =>
loop(xs, result :+ (x, 1))
case Nil => result
}
}
loop(string.toList, Vector.empty[(Char, Int)])
}
println(counterOccur("aabcdddeabb"))
Second solution that does not use recursion. It works the same, but instead of the recursion it is using foldLeft.
def counterOccur2(string: String): Vector[(Char, Int)] = {
string.foldLeft(Vector.empty[(Char, Int)])((r, v) => {
val lastElementIndex = r.size - 1
if (r.lastOption.exists(lv => lv._1.equals(v))) {
r.updated(lastElementIndex, (v, r(lastElementIndex)._2 + 1))
} else {
r :+ (v, 1)
}
})
}
println(counterOccur2("aabcdddeabb"))
You can use a very simple foldLeft to accumulate. You also don't need toCharArray and toList because strings are implicitly convertible to Seq[Char]:
"aabcdddeabb".foldLeft(collection.mutable.ListBuffer[(Char,Int)]()){ (acc, elm) =>
acc.lastOption match {
case Some((c, i)) if c == elm =>
acc.dropRightInPlace(1).addOne((elm, i+1))
case _ =>
acc.addOne((elm, 1))
}
}
Here is a solution using foldLeft and a custom State case class:
def countConsecutives[A](data: List[A]): List[(A, Int)] = {
final case class State(currentElem: A, currentCount: Int, acc: List[(A, Int)]) {
def result: List[(A, Int)] =
((currentElem -> currentCount) :: acc).reverse
def nextState(newElem: A): State =
if (newElem == currentElem)
this.copy(currentCount = this.currentCount + 1)
else
State(
currentElem = newElem,
currentCount = 1,
acc = (this.currentElem -> this.currentCount) :: this.acc
)
}
object State {
def initial(a: A): State =
State(
currentElem = a,
currentCount = 1,
acc = List.empty
)
}
data match {
case a :: tail =>
tail.foldLeft(State.initial(a)) {
case (state, newElem) =>
state.nextState(newElem)
}.result
case Nil =>
List.empty
}
}
You can see the code running here.
One possibility is to use the unfold method. This method is defined for several collection types, here I'm using it to produce an Iterator (documented here for version 2.13.8):
def spans[A](as: Seq[A]): Iterator[Seq[A]] =
Iterator.unfold(as) {
case head +: tail =>
val (span, rest) = tail.span(_ == head)
Some((head +: span, rest))
case _ =>
None
}
unfold starts from a state and applies a function that returns, either:
None if we want to signal that the collection ended
Some of a pair that contains the next item of the collection we want to produce and the "remaining" state that will be fed to the next iteration.
In this example in particular, we start from a sequence of A called as (which can be a sequence of characters) and at each iteration:
if there's at least one item
we split head and tail
we further split the tail into the longest prefix that contains items equal to the head and the rest
we return the head and the prefix we got above as the next item
we return the rest of the collection as the state for the following iteration
otherwise, we return None as there's nothing more to be done
The result is a fairly flexible function that can be used to group together spans of equal items. You can then define the function you wanted initially in terms of this:
def spanLengths[A](as: Seq[A]): Iterator[(A, Int)] =
spans(as).map(a => a.head -> a.length)
This can be probably made more generic and its performance improved, but I hope this can be an helpful example about another possible approach. While folding a collection is a recursive approach, unfolding is referred to as a corecursive one (Wikipedia article).
You can play around with this code here on Scastie.
For
str = "aabcdddeabb"
you could extract matches of the regular expression
rgx = /(.)\1*/
to obtain the array
["aa", "b", "c", "ddd", "e", "a", "bb"]
and then map each element of the array to the desired string.1
def counterOccur(str: String): List[(Char, Int)] = {
"""(.)\1*""".r
.findAllIn(str)
.map(m => (m.charAt(0), m.length)).toList
}
counterOccur("aabcdddeabb")
#=> res0: List[(Char, Int)] = List((a,2), (b,1), (c,1), (d,3), (e,1), (a,1), (b,2))
The regular expression reads, "match any character and save it to capture group 1 ((.)), then match the content of capture group 1 zero or more times (\1*).
1. Scala code kindly provided by #Thefourthbird.

Deletion of duplicate node in Linked List

Program to delete all the occurence of duplicate nodes from the linked list is written below. In the code, we are return new head of linked list after deletion as "dummy.next" but in starting dummy is pointing towards head so if we delete head, then dummy.next should also return the deleted node then why is it returning the new head?
Example input : 1 1 1 2 3
Output:2 3
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode n = dummy;
while (n.next != null && n.next.next != null) {
if (n.next.val == n.next.next.val) {
int duplicate = n.next.val;
while (n.next != null && n.next.val == duplicate) {
n.next = n.next.next;
}
} else {
n = n.next;
}
}
return dummy.next;
}
}
P.S- I do not want to return the deleted node, I want to return the new head and I just want to understand the logic behind this.
Work with a simpler example and you'll understand. Consider a list with just 2 nodes.
1 -> 1*
^
Head
(* is to denote visual distinction)
You create a new dummy node and point its next to Head
0 -> 1 -> 1*
^ ^
dummy Head
Then, you start your iteration from dummy (by doing n = dummy)
0 -> 1 -> 1*
^ ^
n,dummy Head
You enter the loop and you enter the if condition. The fact that you're changing n's next, also changes dummy's next.
0 -> 1* <- 1
^ ^
n,dummy Head
In this way, you keep moving dummy's next as long as the consecutive values are same. Once you encounter a different value, then you march n forward and leave dummy.next pointing to the head.
Remove Duplicate Nodes From Unsorted List: https://github.com/jayesh-tanna/coding-problem-solution/blob/master/DataStructures/SinglyLinkList/RemoveDuplicateNodesFromUnsortedList.java
Remove Duplicates From Sorted List: https://github.com/jayesh-tanna/coding-problem-solution/blob/master/DataStructures/SinglyLinkList/RemoveDuplicatesFromSortedList.java

Maximum element in a tree

I have the following ADT implementation in Scala.
How to find the maximum element in the tree? Can I introduce some helper function, and if yes, then how?
abstract class MySet {
def max: Int
def contains(tweet: Tweet): Boolean = false
}
class Empty extends MySet {
def max: throw new NoSuchElementExeption("max called on empty tree")
def contains(x: Int): Boolean =
if (x < elem) left.contains(x)
else if (elem < x) right.contains(x)
else true
}
class Node(elem: Int, left: MySet, right: MySet) extends Set {
def max: { ... }
def contains(x: Int): Boolean =
if (x < elem) left.contains(x)
else if (elem < x) right.contains(x)
else true
}
I found a solution in Haskell which feels quite intuitive can I convert it to Scala somehow?
data Tree a = Nil | Node a (Tree a) (Tree a)
maxElement Nil = error "maxElement called on empty tree"
maxElement (Node x Nil Nil) = x
maxElement (Node x Nil r) = max x (maxElement r)
maxElement (Node x l Nil) = max x (maxElement l)
maxElement (Node x l r) = maximum [x, maxElement l, maxElement r]
Update
I am not interested in copying the Haskell code in Scala instead I think Haskell version is more intuitive but because of this keyword and other stuff in Object oriented language. How can I write the equivalent code in object oriented style without pattern matching?
Your tree is heterogeneous, which means that each node can be either a full node with a value, or an empty leaf. Hence you need to distinguish which is which, otherwise you can call max on an empty node. There are many ways:
Classic OOP:
abstract class MySet {
def isEmpty: Boolean
...
}
class Empty extends MySet {
def isEmpty = true
...
}
class Node(...) extends MySet {
def isEmpty = false
...
}
So you do something like this:
var maxElem = elem
if(!left.isEmpty)
maxElem = maxElem.max(left.max)
end
if(!right.isEmpty)
maxElem = maxElem.max(right.max)
end
Since JVM has class information at runtime you can skip the definition of isEmpty:
var maxElem = elem
if(left.isInstanceOf[Node])
maxElem = maxElem.max(left.asInstanceOf[Node].max)
end
if(left.isInstanceOf[Node])
maxElem = maxElem.max(right.asInstanceOf[Node].max)
end
(asInstanceOf is not required if you defined max in MySet, but this pattern covers the case when you didn't)
Well, Scala has a syntactic sugar for the latter, and not surprisingly it's the pattern matching:
var maxElem = elem
left match {
case node: Node =>
maxElem = maxElem.max(node.max)
case _ =>
}
right match {
case node: Node =>
maxElem = maxElem.max(node.max)
case _ =>
}
maxElem
You can take it slightly further and write something like this:
def max = (left, right) match {
case (_: Empty, _: Empty) => elem
case (_: Empty, node: Node) => elem.max(node.max)
case (node: Node, _: Empty) => elem.max(node.max)
case (leftNode: Node, rightNode: Node) =>
elem.max(leftNode.max).max(rightNode.max)
}
If you don't want to use pattern matching, you will need to implement an isEmpty operation or its equivalent, to avoid calling max on an empty set.
The important thing is how the tree is organized. Based on the implementation of contains, it looks like you have an ordered tree (a "binary search tree") where every element in the left part is less than or equal to every element in the right part. If that's the case, your problem is fairly simple. Either the right sub tree is empty and the current element is the max, or the max element of the tree is the max of the right sub tree. That should be a simple recursive implementation with nothing fancy required.
Full disclosure, still learning Scala myself, but here is two versions I came up with (which the pattern match looks like a fair translation of the Haskell code)
sealed trait Tree {
def max: Int
def maxMatch: Int
}
case object EmptyTree extends Tree {
def max = 0
def maxMatch = 0
}
case class Node(data:Int,
left:Tree = EmptyTree,
right:Tree = EmptyTree) extends Tree {
def max:Int = {
data
.max(left.max)
.max(right.max)
}
def maxMatch: Int = {
this match {
case Node(x,EmptyTree,EmptyTree) => x
case Node(x,l:Node,EmptyTree) => x max l.maxMatch
case Node(x,EmptyTree,r:Node) => x max r.maxMatch
case Node(x,l:Node,r:Node) => x max (l.maxMatch max r.maxMatch)
}
}
}
Tests (all passing)
val simpleNode = Node(3)
assert(simpleNode.max == 3)
assert(simpleNode.maxMatch == 3)
val leftLeaf = Node(1, Node(5))
assert(leftLeaf.max == 5)
assert(leftLeaf.maxMatch == 5)
val leftLeafMaxRoot = Node(5,
EmptyTree, Node(2))
assert(leftLeafMaxRoot.max == 5)
assert(leftLeafMaxRoot.maxMatch == 5)
val nestedRightTree = Node(1,
EmptyTree,
Node(2,
EmptyTree, Node(3)))
assert(nestedRightTree.max == 3)
assert(nestedRightTree.maxMatch == 3)
val partialFullTree = Node(1,
Node(2,
Node(4)),
Node(3,
Node(6, Node(7))))
assert(partialFullTree.max == 7)
assert(partialFullTree.maxMatch == 7)

remove elements from link list whose sum equals to zero

Given a list in form of linked list, I have to canceled out all the resources whose sum up to 0(Zero) and return the remaining list.
Like
6 -6 3 2 -5 4 returns 4
8 10 4 -1 -3 return 8 10
I only need algorithm to solve this question.
this is actually the classic subset sum problem which is NP-complete
see on wiki or google it to see articles about that
The following function just prints the nodes except the ones which are canceled out, you can make it push to a new list and return.
void printExCancel( node* head )
{
node* start = head;
node* end;
while ( start )
{
bool mod = false;
int sum = 0;
end = start;
while ( end )
{
sum += end->data;
if ( sum == 0 )
{
start = end;
mod = true;
break;
}
end = end->next;
}
if ( mod == false ) {
//push to new list
printf( "%d\n", start->data );
}
//else {
// call funtion to delete from start to end
//}
start = start->next;
}
}
Assumption: Only consecutive elements when summed to zero can be removed.
Approach Followed:
1. Push the non-zero elements of the link list to a stack.
2. On occurrence of a non zero element:
(a) Iterate stack, pop each element and keep adding to the non-zero element.
(b) Keep adding the pop element to a list.
(c) If the value is zero (that means then by now you have removed ) break stack iteration.
(d) If stack is Empty & the sum != 0 add the list elements to stack along with the non-zero one
Try Following Code:
public class ElementSumNonZero {
private static Node head;
private static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
private void removeNonZeroElements(Node root) {
Node start = root;
Stack<Node> stack = new Stack<>();
boolean flag = false;
List<Node> list = new ArrayList<>();
while (start != null) {
if (start.data > 0)
stack.push(start);
else {
int sum = start.data;
flag = false;
while (!stack.isEmpty()) {
Node temp = stack.pop();
sum += temp.data;
if (sum == 0) {
flag = true;
list.clear();
break;
}
list.add(temp);
}
if (!flag) {
list.forEach(i -> stack.add(i));
stack.add(start);
}
}
start = start.next;
}
stack.forEach(i -> System.out.print(i.data +" -> "));
System.out.println("NULL");
}
// Driver program to test above functions
public static void main(String[] args) {
ElementSumNonZero list = new ElementSumNonZero();
ElementSumNonZero.head = new Node(6);
ElementSumNonZero.head.next = new Node(-6);
ElementSumNonZero.head.next.next = new Node(8);
ElementSumNonZero.head.next.next.next = new Node(4);
ElementSumNonZero.head.next.next.next.next = new Node(-12);
ElementSumNonZero.head.next.next.next.next.next = new Node(9);
ElementSumNonZero.head.next.next.next.next.next.next = new Node(8);
ElementSumNonZero.head.next.next.next.next.next.next.next = new Node(-8);
list.removeNonZeroElements(head);
}
}
Test 0
original: {6, -6,6, 8, 4, -12, 9, 8, -8}
canceled out: {9}
Test 1
original: {4, 6, -10, 8, 9, 10, -19, 10, -18, 20, 25}
canceled out: {20, 25}
We can create the resultant stack into a link list and return from "removeNonZeroElements" method.
Please correct me and suggest ways we can make this code efficient.
Following python code also passes both the testcases:
class Node():
def __init__(self,data):
self.data = data
self.next = None
class Linkedlist():
def __init__(self):
self.head = None
def append(self,data):
new_node = Node(data)
h = self.head
if self.head is None:
self.head = new_node
return
else:
while h.next!=None:
h = h.next
h.next = new_node
def remove_zeros_from_linkedlist(self, head):
stack = []
curr = head
list = []
while (curr):
if curr.data >= 0:
stack.append(curr)
else:
temp = curr
sum = temp.data
flag = False
while (len(stack) != 0):
temp2 = stack.pop()
sum += temp2.data
if sum == 0:
flag = True
list = []
break
elif sum > 0:
list.append(temp2)
if not flag:
if len(list) > 0:
for i in range(len(list)):
stack.append(list.pop())
stack.append(temp)
curr = curr.next
return [i.data for i in stack]
if __name__ == "__main__":
l = Linkedlist()
l.append(4)
l.append(6)
l.append(-10)
l.append(8)
l.append(9)
l.append(10)
l.append(-19)
l.append(10)
l.append(-18)
l.append(20)
l.append(25)
print(l.remove_zeros_from_linkedlist(l.head))
'''Delete the elements in an linked list whose sum is equal to zero
E.g-->> 6 -6 8 4 -12 9 8 -8
the above example lists which gets canceled :
6 -6
8 4 -12
8 -8
o/p : 9
case 3 : 4 6 -10 8 9 10 -19 10 -18 20 25
O/P : 20 25'''
#v_list=[6 ,-6, 8, 4, -12, 9, 8, -8]
#Building Nodes
class Node():
def __init__(self,value):
self.value=value
self.nextnode=None
#Class Linked List for Pointing Head and Tail
class LinkedList():
def __init__(self):
self.head=None
def add_element(self,value):
node=Node(value)
if self.head is None:
self.head=node
return
crnt_node=self.head
while True:
if crnt_node.nextnode is None:
crnt_node.nextnode=node
break
crnt_node=crnt_node.nextnode
def print_llist(self):
crnt_node=self.head
v_llist=[]
while True:
print(crnt_node.value,end='->')
v_llist.append(crnt_node.value) # storing data into list
if crnt_node.nextnode is None:
break
crnt_node=crnt_node.nextnode
print('None')
return v_llist
def print_modified_llist(self):
p_add=0
v_llist=self.print_llist()
#going till the second last element of list and then trying to print requested o/p
for i in range(len(v_llist)-1):
p_add=p_add+v_llist[i]
if v_llist[-1]>0 and p_add>0:
print(p_add,v_llist[-1])
elif v_llist[-1]<0 and p_add>0:
print(p_add+v_list[-1])
elif v_llist[-1]<0 and p_add<0:
print(v_llist[-1],p_add)
sll=LinkedList()
sll.add_element(4)
sll.print_llist()
sll.add_element(6)
sll.print_llist()
sll.add_element(-10)
sll.print_llist()
sll.add_element(8)
sll.print_llist()
sll.add_element(9)
sll.print_llist()
sll.add_element(10)
sll.print_llist()
sll.add_element(-19)
sll.print_llist()
sll.add_element(10)
sll.print_llist()
sll.add_element(-18)
sll.print_llist()
sll.add_element(20)
sll.print_llist()
sll.add_element(25)
sll.print_llist()
sll.print_modified_llist()
Remove elements with consecutive sum = K.
In your case K = 0
Append Node with value zero at the starting of the linked list.
Traverse the given linked list.
During traversal store the sum of the node value till that node with the
reference of the current node in an unordered_map.
If there is Node with value (sum – K) present in the unordered_map then delete
all the nodes from the node corresponding to value (sum – K) stored in map to the
current node and update the sum as (sum – K).
If there is no Node with value (sum – K) present in the unordered_map, then
stored the current sum with node in the map.

Resources