Learning basic graph traversal algorithms is important for any software developer to crack coding rounds of interviews at top tech companies.

Breadth-first search is one such graph algorithm, which helps solve easy as well as advanced graph problems. Knowing this algorithm can boost your chances of clearing tech interview questions on data structure and algorithms.

• What Is Graph Traversal?
• What Is BFS?
• Applications of BFS
• How Does BFS Work?
• BFS Algorithm
• BFS Pseudocode
• BFS Code
• BFS for Disconnected Graph
• BFS vs. DFS
• BFS FAQs

## What Is Graph Traversal?

Graph traversal is the process of visiting every vertex and edge of a graph at least once. The order in which the vertices are visited is important. There may be many such orders, but the challenge is to find the traversal technique best suited to solve a particular problem.

## What Is BFS?

Breadth-first search (BFS) is a graph search and traverse algorithm used to solve many programming and real-life problems. It follows a simple, level-based approach. We can easily solve many problems in computer science by modeling them in terms of graphs. For example: analyzing networks, mapping routes, scheduling, and more.

## BFS Applications

• Finding the shortest path: In an unweighted graph, the shortest path between two nodes is the path with the least number of edges. BFS can be used to find the shortest path between a source node and all the remaining nodes in an unweighted graph.
• Finding the minimum spanning tree: After some modifications, this algorithm can be used to find the minimum spanning tree for unweighted graphs.
• Detecting a cycle: This algorithm can be used to detect a cycle in graphs.
• Finding a path: We can use BFS to check whether a path exists between two nodes.
• Peer-to-peer networks: In P2P networks, like BitTorrent, BFS is used to find all neighbor nodes.
• Broadcasting networks: In network broadcasting, broadcasted packets are guided by the BFS algorithm to reach all target nodes.
• GPS navigation systems: BFS is used to find all neighboring locations.
• Search engine crawlers: The main idea behind crawlers is to start from the source page, follow all links from that source to other pages, and keep repeating the same until the objective for crawling is completed.
• Social networking websites: We can find the number of people within a given distance “k” from a person in a social network using BFS.
• Connected component: We can use BFS to find all the nodes within a connected component of a graph.
• Bipartite: This algorithm can be used to check if a graph is bipartite.

## How Does BFS Work?

The BFS algorithm traverses the graph across its breadth. It's a layerwise traversal algorithm. BFS starts traversing the graph from a chosen “root” node, say Source, and explores all of its neighbor nodes at its next depth before moving on to the other nodes.

Let’s look at the algorithm to understand this better.

## BFS Algorithm

• Step 1: Create an empty queue to store the nodes to be visited and a boolean vector to track the visited nodes. Initially, no node is visited.
• Step 2: Choose a starting node, mark it visited, and add it to the queue.
• Step 3: Extract the front item of the queue, add it to the BFS order, and traverse through the list of that node's adjacent nodes.
• Step 4: If a node in that list has not been already visited, mark it visited, and add it to the back of the queue.
• Step 5: Keep repeating steps 3 and 4 until the queue is empty.

Let’s take an example. We’ll use an undirected graph with six vertices.

We first choose a node to start BFS and put it in the queue after marking it “visited.” In this case, we have chosen 0.

We will repeatedly pop the front element of the queue, traverse its neighboring nodes, and add it to “BFS Order.” Currently, we have 0 at the front of the queue, and none of its neighbors are visited. So, we’ll mark them as visited and add all of them to the queue.

Now, we have node 1 at the front of the queue. It has only two neighbors, 0 and 3, which have been marked visited in a previous step. So, we'll move on to the next step.

Here, we have 3 at the front of the queue. It has only one unvisited neighbor, 4. So, we will mark it visited and add it to the queue.

For node 2, we add its unvisited neighbor 5 to the queue.

For node 4, all its neighbors are already visited — we move on to the next step.

After extracting 5 from the queue, all the graph elements have been visited, and there are no elements left in the queue. BFS on this graph is complete.

If you look closely, you will notice that we have visited the nodes layerwise, that is, in the order of their level. Let’s understand what that means.

A level structure of an undirected graph is a partition of the vertices into subsets that are at the same distance from a given root vertex. Here:

• On level 0, we have only node 0, the root vertex
• On level 1, we have 1, 3, and 2
• On the last level, we have 4 and 5

Now, if you observe the obtained BFS Order, we have visited the nodes in the order of their levels.

## BFS Pseudocode

Getting the hang of it? Here’s the pseudocode for BFS. Go ahead and implement it in a programming language of your choice.

``````

BFS (graph G, int start_node)
create a queue Q
mark start_node as visited.
Q.enqueue(start_node)
while (Q is not empty)
curr_node  =  Q.dequeue( )
for all neighbours adj_node of curr_node in Graph G
``````

`‍`

## `BFS Code`

`We’ve chosen C++ to demonstrate how the code works. You can implement the same in C, Java, Python, or any other programming language.`

``````
// C++ implementation of BFS
#include
using namespace std;

// Function to add the edge in an undirected graph
void addEdge(vector g[], int u, int v) {
g[u].push_back(v);
g[v].push_back(u);
}

// BFS Function for node 'root'
void BFS(vector g[], vector &visited, int root) {

// Declare a queue to store all the unvisited nodes of root
queue q;

// Mark root as visited
visited[root] = true;
q.push(root);

while(!q.empty()) {
// Get the front element of the queue
int u = q.front();
q.pop();
cout << u << " ";

// Get all neighboring nodes of the current element u.
for (auto v : g[u]) {
/* If the neighboring node v has not been visited,
then mark it visited and add it to the queue. */
if (!visited[v]) {
visited[v] = true;
q.push(v);
}
}
}
}

int main() {

// Number of nodes/vertices
int V = 6;
// vector array to store the edges of the graph
vector g[V];
/* boolean vector to store the visited status
of the nodes. Initially all marked false. */
vector visited(V, false);

// Adding a few edges to the graph

cout << "The BFS Traversal is : \n";

// Calling the BFS function with root node 0
BFS(g, visited, 0);

return 0;
}
``````

`‍`

### `Code Output`

`The BFS Traversal is: 0 1 3 2 4 5`

### `BFS Complexity`

#### `Time Complexity`

`In this algorithm, we traverse each edge and each node at least once. Therefore, the time complexity can be expressed as O(V + E) — here, V is the number of nodes and E is the number of edges. `

`It is important to note that the number of edges in a graph can vary from 0 to n * (n -1) / 2 in an undirected graph. And so: `

• `Best-case time complexity: O(V), when the graph is very sparse`
• `Worst-case time complexity: O(V2), when the graph is very dense.`

`Another implementation of BFS uses an adjacency matrix instead of an adjacency list (which we have used here) for storing the graph. In that case, the time complexity will always be O(V2).`

`If the graph is a tree, then the complexity becomes O(V), as the number of edges in a tree equals one less than the number of vertices.`

#### `Space Complexity`

`The space complexity of the algorithm is O(V). In both implementations of BFS (using adjacency list and adjacency matrix), the extra space required is in the order of V (for the queue and the boolean vector visited). `

`The space required for the graph representation is O(V + E) for an adjacency list and O(V2) for an adjacency matrix representation.`

## `BFS for Disconnected Graph`

`In the above implementation, we assumed that the graph is connected — all the nodes are reachable from any node. But, we may have to work on disconnected graphs too in some scenarios. `

`With a little modification to the above implementation, we can apply BFS on disconnected graphs too.`

`Following is an example of a disconnected graph (with 8 nodes) and the program to traverse the graph using BFS.`

### `BFS Code for Disconnected Graph`

``````
// C++ implementation of BFS
#include
using namespace std;

// Function to add the edge in an undirected graph
void addEdge(vector g[], int u, int v) {
g[u].push_back(v);
g[v].push_back(u);
}

// BFS Function for node 'root'
void BFS(vector g[], vector &visited, int root) {

// Declare a queue to store all the unvisited nodes of root
queue q;

// Mark root as visited
visited[root] = true;
// Add root to the queue
q.push(root);

while(!q.empty()) {
// Getting the queue’s front element
int u = q.front();
q.pop();
cout << u << " ";

// Get all neighboring nodes of the current element u.
for (auto v : g[u]) {
/* If the neighboring node v has not been visited,
then mark it visited and add it to the queue. */
if (!visited[v]) {
visited[v] = true;
q.push(v);
}
}
}

// Adding a line to separate different components of the graph
cout << '\n';
}

int main() {

// Number of nodes/vertices
int V = 8;
// vector array to store the edges of the graph
vector g[V];
/* boolean vector to store the visited status
of the nodes initially all marked false */
vector visited(V, false);

// Adding a few edges to the graph

cout << "The BFS Traversal is : \n";

/* Calling the BFS function on vertices that
has not been visited yet */
for (int i = 0; i < V; i++)
if (!visited[i])
BFS(g, visited, i);

return 0;
}
``````

`‍`

#### `Output`

`The BFS Traversal is: 0 1 3 2 4 `

`5 6 7`

## `BFS vs. DFS`

`To learn more, check out our article on depth-first search.`

## `BFS FAQs`

`Question 1: How can BFS be used to detect a cycle in an undirected graph?`

`Answer: We can detect if an undirected graph has a cycle by performing a BFS traversal of the given graph. For every visited vertex “v,” if there is an adjacent “u” such that u is already visited and u is not a parent of v, then there is a cycle in the graph. `

`If we don’t find such an adjacent node for any vertex, we can conclude that there is no cycle in the graph. Note that we have assumed that there are no parallel edges between any two vertices in the graph; otherwise, we can say that the graph contains a cycle without even applying BFS.`

`Question 2: Why does BFS use the “queue” data structure over other data structures like “stack”?`

`Answer: The First In First Out (FIFO) concept of a queue ensures that things that are discovered first are explored first, before exploring those that are discovered subsequently — this is the key for this algorithm. Therefore, a queue is the most optimum data structure for implementing BFS.  `

`Stacks are exactly the opposite of queues. Stacks apply the Last In First Out (LIFO) concept, which is optimum for the depth-first search algorithm.`

`Question 3: Can we find the shortest path between two nodes using BFS?`

`Answer: We can find the shortest paths between nodes using BFS but only for an unweighted graph. For a given node “u” of a  connected graph “G,” we can find the shortest path between u and all other nodes of the graph G by applying BFS on the graph with the root node as u. `

`We can do this by storing the immediate parent of each node in an array while visiting the vertices in the BFS function and then creating the path for each node using the parent array. The parent of a node is its neighbor that was visited the earliest. `

`Let’s suppose we have the parent array “p” of size “V,” for a graph G with V vertices, and node 0 is the root. Suppose we want to find the path between the root node and all the other nodes of the graph: `

`For all i, where 0 < i < V holds, Let pi be the parent of node i. p can be set as -1. `

`The following pseudocode will do the job:`

``````
for i : 1 to V - 1
j = i
while p[j] != -1
print(j)
j = p[j]
``````

`Note that the above pseudocode will print the path in reversed order.`

`Question 4: Is BFS a complete and optimal algorithm?`

`Answer: If an algorithm is complete, it means that if at least one solution exists, then the algorithm is guaranteed to find a solution in a finite amount of time.`

`If a search algorithm is optimal, it means when it finds a solution, it finds the best solution.`

`BFS is both complete and optimal.`

## `Are You Ready to Nail Your Next Coding Interview?`

`Basic graph traversal algorithms can help you solve many questions during your tech interview as a software developer. If you’re looking for guidance and support to nail these questions and more, sign up for our free webinar. `

`As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!`

`Sign up now!`

`--------`

`Article contributed by Shivam Gupta`

### `Attend our Free Webinar on How to Nail Your Next Technical Interview`

#### `Recommended Posts`

`Fork in C`
`Join Function in Python `
`Vector in C++ STL`
`All Posts`
``` \$(document).ready(function() { var jqxhr = \$.getJSON( "https://get.geojs.io/v1/ip/geo.json", function(data) {}) .done(function(data) { v_city = data.city; v_ccode = data.country_code; }) .fail(function(data) { // }); const c_date = new Date(); const c_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; if( (c_date.getDate() >= 1) && (c_date.getDate() <= 25)){ \$('.cohort-month').html(c_months[c_date.getMonth()] +" "+ c_date.getFullYear()); \$('.cohort-month-full').html(c_months[c_date.getMonth()-1] +" "+ c_date.getFullYear()); }else{ \$('.cohort-month').html(c_months[c_date.getMonth()+1] +" "+ c_date.getFullYear()); \$('.cohort-month-full').html(c_months[c_date.getMonth()] +" "+ c_date.getFullYear()); } }); window.cookieconsent.initialise({ "palette": { "popup": { "background": "#3996d2", "text": "#ffffff" }, "button": { "background": "#00d1b4", "text": "#ffffff" } }, "theme": "classic", "content": { "message": "We use cookies to enable the best possible experience on our site and to optimize the content for you. If you continue surfing you agree.", "href": "https://www.interviewkickstart.com/privacy-policy" } }); function getAllUrlParams(url) { var queryString = url ? url.split('?') : window.location.search.slice(1); var utmobj = {}; if (queryString) { queryString = queryString.split('#'); var arr = queryString.split('&'); for (var i = 0; i < arr.length; i++) { var a = arr[i].split('='); var paramName = a; var paramValue = typeof (a) === 'undefined' ? true : a; paramName = paramName.toLowerCase(); if (paramName.match(/\[(\d+)?\]\$/)) { var key = paramName.replace(/\[(\d+)?\]/, ''); if (!utmobj[key]) utmobj[key] = []; if (paramName.match(/\[\d+\]\$/)) { var index = /\[(\d+)\]/.exec(paramName); utmobj[key][index] = paramValue; } else { utmobj[key].push(paramValue); } } else { if (!utmobj[paramName]) { utmobj[paramName] = paramValue; } else if (utmobj[paramName] && typeof utmobj[paramName] === 'string'){ utmobj[paramName] = [utmobj[paramName]]; utmobj[paramName].push(paramValue); } else { utmobj[paramName].push(paramValue); } } } } return utmobj; } function create_UUID() { function _p8(s) { var p = (Math.random().toString(16)+"000000000").substr(2,8); return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ; } return _p8() + _p8(true) + _p8(true) + _p8(); } var visitor_id = getCookie("unique_visitor_id4"); var expdate = new Date(); expdate.setTime(expdate.getTime()+(365*24*60*60*1000)); if(visitor_id == ""){ setCookie("unique_visitor_id4",create_UUID()); visitor_id = getCookie("unique_visitor_id4"); } var referrer = document.referrer; var utm_params_url; let calendly_param = getAllUrlParams(); \$("#iksiteurl").val(iksite_url); if(calendly_param['invitee_first_name'] != undefined){ \$("#invitee_first_name").val(decodeURIComponent(calendly_param['invitee_first_name'])); \$("#invitee_last_name").val(decodeURIComponent(calendly_param['invitee_last_name'])); \$("#invitee_email").val(decodeURIComponent(calendly_param['invitee_email'])); \$("#answer_1").val(decodeURIComponent(calendly_param['answer_1'])); \$("#utm_source").val(decodeURIComponent(calendly_param['utm_source'])); \$("#utm_medium").val(decodeURIComponent(calendly_param['utm_medium'])); \$("#utm_campaign").val(decodeURIComponent(calendly_param['utm_campaign'])); \$("#salesforce_uuid").val(decodeURIComponent(calendly_param['salesforce_uuid'])); \$("#gclid").val(decodeURIComponent(calendly_param['gclid'])); \$("#msclkid").val(decodeURIComponent(calendly_param['msclkid'])); \$("#fbclid").val(decodeURIComponent(calendly_param['fbclid'])); \$("#event_start_time").val(decodeURIComponent(calendly_param['event_start_time'])); \$("#event_end_time").val(decodeURIComponent(calendly_param['event_end_time'])); \$("#user_id").val(visitor_id); utm_params_url = {}; } else{ utm_params_url = getAllUrlParams(); } if(utm_params_url['gh_jid'] != undefined){ utm_params_url = {}; \$('.careers-sec1, .careers-sec2, .careers-sec3, .careers-sec4').hide(); } let isEmpty = jQuery.isEmptyObject(utm_params_url); let r_visit = read_cookie("v_latest"); if(isEmpty && (r_visit == null)){ bake_organic_cookie(); } else if(!isEmpty && (r_visit == null)){ bake_cookie("v_latest", utm_params_url); if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1) bake_cookie_history("v_history", utm_params_url); } else if(isEmpty && (r_visit != null)){ if(r_visit['utm_source'] != "Organic") { bake_organic_cookie(); } } else{ if(!isDuplicateCookie(utm_params_url, r_visit)){ bake_cookie("v_latest", utm_params_url); if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1) bake_cookie_history("v_history", utm_params_url); } } function isCookieSizeExceeded(){ let c_size = 15; var h_cookie = read_cookie("v_history"); if (h_cookie == null) return; if(h_cookie.length >= c_size){ h_cookie.shift(); bake_cookie("v_history", h_cookie); } } function isDuplicateCookie(utm_params, recent_visit){ if((utm_params['utm_source'] == recent_visit['utm_source']) && (utm_params['utm_medium'] == recent_visit['utm_medium']) && (utm_params['utm_campaign'] == recent_visit['utm_campaign']) && (utm_params['utm_adset'] == recent_visit['utm_adset']) && (utm_params['utm_content'] == recent_visit['utm_content']) && (utm_params['utm_term'] == recent_visit['utm_term']) && (utm_params['fbclid'] == recent_visit['fbclid'])) { return true; } else{return false;} } function bake_cookie_history(name, value) { isCookieSizeExceeded(); var visits_history = []; var iksutmhistory = read_cookie(name); if(iksutmhistory == "" || iksutmhistory == null){ var utmstring = value; utmstring.timestamp = \$.now(); visits_history.push(utmstring); var cookie = [name, '=', JSON.stringify(visits_history), ';expires','=', expdate.toGMTString(), '; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } else { var result = document.cookie.match(new RegExp(name + '=([^;]+)')); result && (result = JSON.parse(result)); var newhistoryobj = result.push(value); var cookie = [name, '=', JSON.stringify(result), ';expires','=', expdate.toGMTString(), '; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } } function bake_organic_cookie(){ var organicobj = { "utm_source":"Organic", "utm_medium":"", "utm_campaign":"", "utm_adset":"", "utm_content":"", "utm_term":"", "timestamp":\$.now()}; if(referrer == null || referrer.indexOf(window.location.host.toString()) == -1){ bake_cookie_history("v_history", organicobj); bake_cookie("v_latest", organicobj); } } function bake_cookie(name, value) { var utmstring = value; utmstring.timestamp = \$.now(); var cookie = [name, '=', JSON.stringify(utmstring), ';expires','=', expdate.toGMTString(),'; domain=.', window.location.host.toString(), '; path=/;'].join(''); document.cookie = cookie; } function read_cookie(name) { var result = document.cookie.match(new RegExp(name + '=([^;]+)')); result && (result = JSON.parse(result)); return result; } function setCookie(cname, cvalue) { var d = new Date(); d.setTime(d.getTime() + (365*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } \$('.calendly-link-widget').click(function(){ var active_visit = read_cookie("v_latest"); var visit_history = read_cookie("v_history"); var utm_medium_str=""; for (const property in active_visit) { if (`\${property}` == "utm_medium") { utm_medium_str = utm_medium_str + `\${active_visit[property]}`; } } utm_medium_str = utm_medium_str + ":"; for (const property in active_visit) { if (`\${property}` == "gclid") { utm_medium_str = utm_medium_str + "gclid:" + `\${active_visit[property]}`; } else if (`\${property}` == "msclkid") { utm_medium_str = utm_medium_str + "msclkid:" + `\${active_visit[property]}`; } else if (`\${property}` == "fbclid") { utm_medium_str = utm_medium_str + "fbclid:" + `\${active_visit[property]}`; } } if ( (utm_medium_str.indexOf("gclid") == -1) && (utm_medium_str.indexOf("msclkid") == -1) && (utm_medium_str.indexOf("fbclid") == -1)){ utm_medium_str = utm_medium_str + ":"; } utm_medium_str = utm_medium_str + ":" + visitor_id.toString().replace(/"/g, ""); var utm_campaign="",utm_source="",utm_content="",utm_term=""; for (const property in active_visit) { if (`\${property}` == "utm_campaign") { utm_campaign = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_source") { utm_source = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_content") { utm_content = `\${active_visit[property]}`; } } for (const property in active_visit) { if (`\${property}` == "utm_term") { utm_term = `\${active_visit[property]}`; } } Calendly.initPopupWidget({ url: 'https://calendly.com/interviewkickstart/enrollment-workshop', utm: { utmCampaign: utm_campaign, utmSource: utm_source, utmMedium: utm_medium_str, utmContent: utm_content, utmTerm: utm_term } }); let page_url = window.location.pathname; var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } setTimeout(function(){ location.href = calendlyurl; }, 100); } }); return false; }); \$('.direct-link').click(function(e) { e.preventDefault(); calendlySignup(false,""); }); \$('.lpv5-home-form').click(function(e) { e.preventDefault(); var formstr = '&first_name=' + \$("#lpv5-fname").val() + '&last_name=' + \$("#lpv5-lname").val() + '&a1=' + \$("#lpv5-phone").val() + '&email=' + \$("#lpv5-email").val(); calendlySignup(true, formstr); }); \$('.request-info-close').click(function(e){ \$('.request-info-wrap').css("display","none"); \$('.request-info-wrap').css("opacity",0); }); \$('.btn-webinar-popup').click(function(e){ e.preventDefault(); \$('.request-info-wrap').css("display","flex"); \$('.request-info-wrap').css("opacity",1); let page_url = window.location.pathname; let visit_history = read_cookie("v_history"); var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } } }); }); \$('.form-to-calendly').click(function(e) { e.preventDefault(); var active_visit = read_cookie("v_latest"); var full_phone_number = int_phone.getNumber(intlTelInputUtils.numberFormat.E164); \$("input[name='phone_number[full]'").val(full_phone_number); var formstr = '&first_name=' + \$("#wcalendly-fname").val() + '&last_name=' + \$("#wcalendly-lname").val() + '&a1=' + full_phone_number + '&email=' + encodeURIComponent(\$("#wcalendly-email").val()) + '&salesforce_uuid=' + v_timezone; \$('#wc_utm_source').val(active_visit['utm_source']); \$('#wc_utm_medium').val(active_visit['utm_medium']); \$('#wc_utm_campaign').val(active_visit['utm_campaign']); \$('#wc_gclid').val(active_visit['gclid']); \$('#wc_msclkid').val(active_visit['msclkid']); \$('#wc_timezone').val(v_timezone); \$('#wc_page_url').val(window.location.pathname); \$('#wc_user_id').val(visitor_id); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#wcalendly-fname" ).keypress(function() { \$('.fname-error').addClass('hide'); }); \$( "#wcalendly-lname" ).keypress(function() { \$('.lname-error').addClass('hide'); }); \$( "#wcalendly_pnumber" ).keypress(function() { \$('.mobile-error').addClass('hide'); }); \$( "#wcalendly-email" ).keypress(function() { \$('.email-error').addClass('hide'); }); \$( "#wcalendly-fname, #wcalendly-lname, #wcalendly-email, #wcalendly_pnumber" ).focus(function() { \$('.fname-error, .lname-error, .email-error, .mobile-error').addClass('hide'); }); if( (\$("#wcalendly-fname").val().length == 0) && (\$("#wcalendly-lname").val().length == 0) && (\$("#wcalendly-email").val().length == 0) && (\$("#wcalendly_pnumber").val().length == 0)){ \$('.fname-error, .lname-error, .email-error, .mobile-error').removeClass('hide'); } else if (!name_regex.test(\$("#wcalendly-fname").val()) || \$("#wcalendly-fname").val().length == 0){ \$('.fname-error').removeClass('hide'); }else if (!name_regex.test(\$("#wcalendly-lname").val()) || \$("#wcalendly-lname").val().length == 0){ \$('.lname-error').removeClass('hide'); }else if (!email_regex.test(\$("#wcalendly-email").val()) || \$("#wcalendly-email").val().length == 0){ \$('.email-error').removeClass('hide'); }else if(!phone_regex.test(\$("#wcalendly_pnumber").val()) || \$("#wcalendly_pnumber").val().length == 0){ \$('.mobile-error').removeClass('hide'); }else{ \$(".leadcapturing-form").submit(); calendlySignup(true,formstr); } }); function calendlySignup(isthisForm,formstr) { \$('.loading-overlay').css('display', 'flex'); var calendlyurl = "https://calendly.com/interviewkickstart/enrollment-workshop?"; var active_visit = read_cookie("v_latest"); var visit_history = read_cookie("v_history"); var utm_medium_str = "utm_medium="; for (const property in active_visit) { if (`\${property}` == "utm_medium") { utm_medium_str = utm_medium_str + `\${active_visit[property]}`; } } utm_medium_str = utm_medium_str + ":"; for (const property in active_visit) { if (`\${property}` == "gclid") { utm_medium_str = utm_medium_str + "gclid:" + `\${active_visit[property]}`; } else if (`\${property}` == "msclkid") { utm_medium_str = utm_medium_str + "msclkid:" + `\${active_visit[property]}`; } else if (`\${property}` == "fbclid") { utm_medium_str = utm_medium_str + "fbclid:" + `\${active_visit[property]}`; } } if ( (utm_medium_str.indexOf("gclid") == -1) && (utm_medium_str.indexOf("msclkid") == -1) && (utm_medium_str.indexOf("fbclid") == -1)){ utm_medium_str = utm_medium_str + ":"; } utm_medium_str = utm_medium_str + ":" + visitor_id; for (const property in active_visit) { var ptyn = `\${active_visit[property]}`; if( (`\${property}` != "utm_medium") && (`\${property}` != "msclkid") && (`\${property}` != "fbclid") && (`\${property}` != "gclid") ){ calendlyurl = calendlyurl+`\${property}`+"="+`\${active_visit[property]}`+"&"; } } utm_medium_str = utm_medium_str + "&salesforce_uuid="+v_timezone; calendlyurl = calendlyurl + utm_medium_str; if(isthisForm){ calendlyurl = calendlyurl + formstr; } let page_url = window.location.pathname; var jsonData = {"unique_visitor_id": visitor_id.toString().replace(/"/g, ""), "device_name": "", "page_url": page_url, "visitor_city": v_city, "click_history":JSON.stringify(visit_history)}; \$.ajax({ type: "POST", url: "https://hooks.zapier.com/hooks/catch/9555768/ong6g6o/", data: jsonData, success: function (e) { if(e.status == "success"){ bake_cookie("v_history",""); bake_cookie("v_latest",""); } setTimeout(function(){ location.href = calendlyurl; \$('.loading-overlay').css('display', 'none'); }, 100); } }); } window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-54935903-1', { 'user_id': visitor_id }); \$(document).ready(function () { \$('.btn-sendinblue-subscribe').click(function(e) { e.preventDefault(); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; //var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#sb-fname" ).keypress(function() { \$('.fname-sb-error').addClass('hide'); }); \$( "#sb-email" ).keypress(function() { \$('.email-sb-error').addClass('hide'); }); \$( "#sb-fname, #sb-email" ).focus(function() { \$('.fname-sb-error, .email-sb-error').addClass('hide'); }); if( (\$("#sb-fname").val().length == 0) && (\$("#sb-email").val().length == 0)){ \$('.fname-sb-error, .email-sb-error').removeClass('hide'); } else if (!name_regex.test(\$("#sb-fname").val()) || \$("#sb-fname").val().length == 0){ \$('.fname-sb-error').removeClass('hide'); }else if (!email_regex.test(\$("#sb-email").val()) || \$("#sb-email").val().length == 0){ \$('.email-sb-error').removeClass('hide'); }else{ \$("#form-sendinblue-popup").submit(); setTimeout(function(){ \$('.close-sb-popup').trigger('click'); \$('.subscription-popup').css('right','-400px'); }, 2000); } }); }); idleTimer = null; idleState = false; idleWait = 300000; (function (\$) { \$(document).ready(function () { \$('.nudge-blog').click(function(e) { e.preventDefault(); fbq('track', 'nudge_blog'); window.open(\$(this).attr('href')); }); \$('*').bind('mousemove keydown scroll', function () { clearTimeout(idleTimer); idleState = false; idleTimer = setTimeout(function () { bioEp.showPopup(); idleState = true; }, idleWait); }); \$("body").trigger("mousemove"); }); }) (jQuery) \$( document ).ready(function() { let utm_sendinblue = getAllUrlParams(); \$(".sb_utm_source").val((utm_sendinblue['utm_source'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_source'])); \$(".sb_utm_medium").val((utm_sendinblue['utm_medium'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_medium'])); \$(".sb_utm_campaign").val((utm_sendinblue['utm_campaign'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_campaign'])); \$(".sb_utm_term").val((utm_sendinblue['utm_term'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_term'])); \$(".sb_utm_content").val((utm_sendinblue['utm_content'] == undefined) ? "" : decodeURIComponent(utm_sendinblue['utm_content'])); \$(".sb_page_url").val(decodeURIComponent(window.location.pathname)); \$('a').each(function() { var reg_exp = new RegExp('/' + window.location.host + '/'); if (!reg_exp.test(this.href)) { // External Link Found \$(this).attr('rel','nofollow'); } }); }); var usertimezone; function geoip(json){ usertimezone = json.timezone; } \$(document).ready(function() { /*var utcstr = Date(\$('.webinar-slots-item').find('.utc-date').data('starttime')); var tzstr = String(utcstr.match(/\(([^)]+)\)/)); var tzformat = tzstr.match(/\b(\w)/g); var tz = tzformat.join(''); console.log("Your timezone: "+ tz);*/ var ltz = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join(''); \$('.webinar-slots-item').each(function(){ let localtime = UTLtoLocal(\$(this).find('.utc-date').val(), \$(this).find('.utc-date').data('timezone')); \$(this).find('.slot-radio-date').html(localtime +" "+ltz); \$(this).find('.utc-date').data('local',localtime); if(compareDates(localtime)){ //console.log("Registrations Closed for: "+ localtime); \$(this).hide(); } }); function UTLtoLocal(utcdate, timezone) { let pdtdate = new Date(utcdate); // pdtdate.setHours(pdtdate.getHours() - 1); let theDate = new Date(Date.parse(pdtdate + timezone)); let localDate = theDate.toLocaleDateString('en-US', { weekday: 'short', month: 'long', day: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); return localDate; } function compareDates(eventdate){ let currentdate = new Date(); let edate = new Date(eventdate); if(currentdate.getTime() >= edate.getTime()){ return true; } } int_phone = window.intlTelInput(document.querySelector("#wcalendly_pnumber"), { initialCountry: "auto", geoIpLookup: function(callback) { \$.get('https://get.geojs.io/v1/ip/geo.js', function() {}, "jsonp").always(function(resp) { var countryCode = (resp && resp.country_code) ? resp.country_code : "us"; callback(countryCode); }); }, hiddenInput: "full", utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js" }); \$('.btn-submit-wc-step1').click(function(e) { e.preventDefault(); let active_visit = read_cookie("v_latest"); var full_phone_number = int_phone.getNumber(intlTelInputUtils.numberFormat.E164); \$("input[name='phone_number[full]'").val(full_phone_number); \$('.wc_utm_source').val(active_visit['utm_source']); \$('.wc_utm_medium').val(active_visit['utm_medium']); \$('.wc_utm_campaign').val(active_visit['utm_campaign']); \$('.wc_utm_term').val(active_visit['utm_term']); \$('.wc_utm_content').val(active_visit['utm_content']); \$('.wc_fbclid').val(active_visit['gclid']); \$('.wc_gclid').val(active_visit['gclid']); \$('.wc_msclkid').val(active_visit['msclkid']); \$('.wc_timezone').val(usertimezone); \$('.wc_page_url').val(window.location.pathname); \$('.wc_user_id').val(visitor_id); \$('.wc_hostname').val(window.location.hostname); var name_regex = new RegExp("^[a-zA-Z ]+\$"); var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+\$/; var phone_regex = /^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\$/gm; \$( "#wcalendly-fname" ).keypress(function() { \$('.fname-error').addClass('hide'); }); \$( "#wcalendly-lname" ).keypress(function() { \$('.lname-error').addClass('hide'); }); \$( "#wcalendly_pnumber" ).keypress(function() { \$('.mobile-error').addClass('hide'); }); \$( "#wcalendly-email" ).keypress(function() { \$('.email-error').addClass('hide'); }); \$( "#wcalendly-fname, #wcalendly-lname, #wcalendly-email, #wcalendly_pnumber" ).focus(function() { \$('.fname-error, .lname-error, .email-error, .mobile-error').addClass('hide'); }); if( (\$("#wcalendly-fname").val().length == 0) && (\$("#wcalendly-lname").val().length == 0) && (\$("#wcalendly-email").val().length == 0) && (\$("#wcalendly_pnumber").val().length == 0)){ \$('.fname-error, .lname-error, .email-error, .mobile-error').removeClass('hide'); } else if (!name_regex.test(\$("#wcalendly-fname").val()) || \$("#wcalendly-fname").val().length == 0){ \$('.fname-error').removeClass('hide'); }else if (!name_regex.test(\$("#wcalendly-lname").val()) || \$("#wcalendly-lname").val().length == 0){ \$('.lname-error').removeClass('hide'); }else if (!email_regex.test(\$("#wcalendly-email").val()) || \$("#wcalendly-email").val().length == 0){ \$('.email-error').removeClass('hide'); }else if(!phone_regex.test(\$("#wcalendly_pnumber").val()) || \$("#wcalendly_pnumber").val().length == 0){ \$('.mobile-error').removeClass('hide'); }else{ \$('.wc_fname').val(\$("#wcalendly-fname").val()); \$('.wc_lname').val(\$("#wcalendly-lname").val()); \$('.wc_email').val(\$("#wcalendly-email").val()); \$('.wc_phone').val(full_phone_number); \$(".lead-form-details").hide(); \$(".lead-form-moredetails").show(); \$("#dlc-personal-details").submit(); } }); \$( "input[type=radio]" ).on( "click", function() { \$('.slots-error').addClass('hide'); \$('.wc_webinar_starttime').val(\$( this ).data('starttime')); \$('.wc_webinar_endtime').val(\$( this ).data('endtime')); \$(".slot-booked2").text(\$(this).data('local')); }); \$('.btn-bookthis-slot').click(function(e) { e.preventDefault(); let n = \$( "input:checked" ).length; if( n == 0){ \$('.slots-error').removeClass('hide'); }else{ \$('.wc_slot').val(\$( "input:checked" ).val()); \$('.slots-error').addClass('hide'); \$(".lead-form-slots").hide(); \$(".lead-form-details").show(); \$("#dlc-webinar-slots").submit(); } }); }); ```