## Search Posts

### Popular

View More
```/*Good morning! Here's your coding interview problem for today.
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.*/#include <iostream>using namespace std;
int calcMissing(int* input, int size){	int sum = 0;	int n = 1; //add one to account for missing value	for(int i = 0; i < size; i++)	{	if(input[i] > 0)	{	sum += input[i];	n++;	}	}
//If no numbers higher than 0, answer is 1	if(sum == 0)	return 1;
return (n*(n+1)/2) - sum; //Formula is expectedSum - actualSum	/* expectedSum = n*(n+1)/2, the formula for sum(1, n) */}
int main(){
cout << calcMissing(new int[4]{3, 4, -1, 1}, 4) << endl;	cout << calcMissing(new int[3]{1, 2, 0}, 3) << endl;
//No positive numbers	cout << calcMissing(new int[1]{0}, 1) << endl;}```

### Invert Binary Tree

CodeCatch
2 likes • Oct 15, 2022
JavaScript
```var invertTree = function(root) {    const reverseNode = node => {        if (node == null) {            return null        }        reverseNode(node.left);        reverseNode(node.right);        let holdLeft = node.left;        node.left = node.right;        node.right = holdLeft;        return node;    }
return reverseNode(root);};```

### MongoDB Connection

CodeCatch
2 likes • Oct 15, 2022
JavaScript
```const MongoClient = require('mongodb').MongoClient;const assert = require('assert');
// Connection URLconst url = 'mongodb://localhost:27017';
// Database Nameconst dbName = 'myproject';
// Use connect method to connect to the serverMongoClient.connect(url, function(err, client) {  assert.equal(null, err);  console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();});```
```my_list = ["blue", "red", "green"]
#1- Using sort or srted directly or with specifc keysmy_list.sort() #sorts alphabetically or in an ascending order for numeric data my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest. # You can use reverse=True to flip the order
#2- Using locale and functools import localefrom functools import cmp_to_keymy_list = sorted(my_list, key=cmp_to_key(locale.strcoll))```

View More

### Bubble sort

CodeCatch
0 likes • Nov 19, 2022
Python
```# Python program for implementation of Bubble Sort
def bubbleSort(arr):	n = len(arr)
# Traverse through all array elements	for i in range(n-1):	# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place		for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1			# Swap if the element found is greater			# than the next element			if arr[j] > arr[j+1] :				arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test abovearr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")for i in range(len(arr)):	print ("%d" %arr[i]),```
```const getFollowers = async (req: Request, res: Response) => {  try {    const username = req.params.username || '';
const user = await User.findUnique({      where: { username },      include: { followedBy: true },    });
if (!user) {      res.status(404).json({        error: 'User could not be found',      });      return;    }
const followers = user.followedBy.map(followedBy => {      return {        followerId: followedBy.followerId,      };    });
const followersCount = followers.length;
res.json({ followersCount: followersCount, followers });  } catch (error) {    console.error('getFollowers() error: ', error);    res.status(500).json({      error: `There was an error fetching followers for user with username "\${req.params.username}", please try again later`,    });  }};
const getFollowing = async (req: Request, res: Response) => {  try {    const username = req.params.username || '';
const user = await User.findUnique({      where: { username },      include: { following: true },    });
if (!user) {      res.status(404).json({        error: 'User could not be found',      });      return;    }
const following = user.following.map(following => {      return {        followingId: following.followingId,      };    });
const followingCount = following.length;
res.json({ followingCount: followingCount, following });  } catch (error) {    console.error('getFollowing() error: ', error);    res.status(500).json({      error: `There was an error fetching who is following "\${req.params.username}", please try again later`,    });  }};
const followUser = async (req: Request, res: Response) => {  try {    const username = req.params.username || '';
const user = await User.findUnique({      where: { username },    });
if (!user) {      res.status(404).json({        error: 'User could not be found',      });      return;    }
// dont allow a user to follow themselves    if (req.user.id === user.id) {      res.status(400).json({ error: 'You cannot follow yourself' });      return;    }
//check if a follow relationship already exists    const followrelationship = await prisma.follows.findUnique({      where: {        followerId_followingId: {          followerId: req.user.id,          followingId: user.id,        },      },    });
// check if the follow relationship already exists    if (followrelationship) {      res.status(400).json({ error: 'You are already following this user' });      return;    }
// create the follow relationship    const follow = await prisma.follows.create({      data: {        followerId: req.user.id,        followingId: user.id,      },    });
res.json({ follow });  } catch (error) {    console.error('followUser() error: ', error);    res.status(500).json({      error: `There was an error following "\${req.params.username}", please try again later`,    });  }};
const unfollowUser = async (req: Request, res: Response) => {  try {    const username = req.params.username || '';
const user = await User.findUnique({      where: { username },    });
if (!user) {      res.status(404).json({        error: 'User could not be found',      });      return;    }
// dont allow a user to unfollow themselves    if (req.user.id === user.id) {      res.status(400).json({ error: 'You cannot unfollow yourself' });      return;    }
//check if a follow relationship already exists    const followrelationship = await prisma.follows.findUnique({      where: {        followerId_followingId: {          followerId: req.user.id,          followingId: user.id,        },      },    });
// check if the follow relationship already exists    if (!followrelationship) {      res.status(400).json({ error: 'You are not following this user' });      return;    }
// delete the follow relationship    const follow = await prisma.follows.delete({      where: {        followerId_followingId: {          followerId: req.user.id,          followingId: user.id,        },      },    });
res.json({ follow });  } catch (error) {    console.error('unfollowUser() error: ', error);    res.status(500).json({      error: `There was an error unfollowing "\${req.params.username}", please try again later`,    });  }};```

### Mongoose Model

JoeCamRoberon
0 likes • Mar 11, 2021
JavaScript
```const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({	username: {	type: String,	required: true	},	email: {	type: String,	unique: true,	required: true	},	password: {	type: String,	required: true	},	date: {	type: Date,	default: Date.now	}})
module.exports = User = mongoose.model('user', UserSchema)```
```\$base-color: #036;
@for \$i from 1 through 3 {  ul:nth-child(3n + #{\$i}) {    background-color: lighten(\$base-color, \$i * 5%);  }}```